March 13th, 2003, 03:01 AM
does anyone know how to put a database connection into a session varible in a servlet?or is this possible?
March 13th, 2003, 03:47 AM
You can set any type of object as a session attribute:
You have to cast it when you're getting it back out again:
The only problem is that if you're storing a java.sql.Connection (if that's what you're using) as a session attribute is that you don't know when to close() the connection, because when the session ends, you've lost your pointer to the Connection so you have to wait for the automatic collection to close it, which isn't always the most reliable or efficient.
ObjectType objectName = (ObjectType) session.getAttribute("attributeName");
March 13th, 2003, 04:09 PM
It is generally considered a very bad idea to store a users connection to the database in their session. This keeps the connection open for the life of the session. Typical sessoins are 30 minutes. Databases will deny new connections after a predetermined limit has been reached. This can be anywhere from 10-100. Regardless of the limit, that leaves very little scalability of your web app.
If you are trying to avoid the performance penalty of opening a new connection each time a user accesses a servlet, then I would suggest Connection Pooling. Tomcat has a built in Connection Pool you can use. I believe this link is the how-to to set it up in Tomcat. Using connection pooling will allow you to get a connection each time a user accesses a servlet and return it after the servlet finished running, but without the cost of creating a new connection everytime. The connectoin pool only creates a new connection if all pre-made connections are currently "checked out".
If you are interested I would suggest searching on google and the sun developer forum on tomcat connection pooling. Hope this helps.
Last edited by Nemi; March 13th, 2003 at 04:12 PM.