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

    Join Date
    Feb 2003
    Posts
    15
    Rep Power
    0

    Sessions+database


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

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

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

    Join Date
    Feb 2001
    Location
    Lincoln, NE. USA
    Posts
    2,353
    Rep Power
    117
    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 05:12 PM.

IMN logo majestic logo threadwatch logo seochat tools logo