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 HttpSessionListener
and within sessionDestroyed()
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?
managing a connection pool, may also be an issue. To get a connection from a connection pool you need to use synchronization, which is preventing other threads (clients) to access the connection pool.
您可以实现HttpSessionBindingListener。
You need to explicitly close connection object. You can close collection in finalize method but it is not recommended as finalize may not get called. Better approach is to write and call method which will explicitly close this connection. Creating JDBC connection in constructor is also not recommended.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.