I am creating a Connection object and making jdbc connection in a constructor of a class (DbTest).
Then in another java class(RequestFilter.java), I am initializing this object and storing this instance object in HTTP Session,
DbTest dbtest = new DbTest();
session.setAttribute("dbtest", dbtest);
My question is, is there a way to close the connection object that was created when the session expires? Or will it automatically get closed when it expires?
You can implement
HttpSessionListenerand withinsessionDestroyed()method do the cleanup. However your architecture worries me. You should not store raw JDBC connection in HTTP session!you cannot migrate the HTTP session to another server
You can easily create thousands of open database connections, HTTP sessions are much more lightweight
99.9% of the time your database connections are idle
you aren’t probably handling connection timeouts and other failures
Any reasons to have a connection per user rather than a connection pool?