1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2003
    Rep Power


    does anyone know how to put a database connection into a session varible in a servlet?or is this possible?

  2. #2
  3. kill 9, $$;
    Devshed Supreme Being (6500+ posts)

    Join Date
    Sep 2001
    Shanghai, An tSín
    Rep Power
    You can set any type of object as a session attribute:
    session.setAttribute("attributeName", objectName);
    You have to cast it when you're getting it back out again:
    ObjectType objectName = (ObjectType) session.getAttribute("attributeName");
    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.
  4. #3
  5. No Profile Picture
    Clueless llama
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Feb 2001
    Lincoln, NE. USA
    Rep Power
    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.

IMN logo majestic logo threadwatch logo seochat tools logo