I am working on Servlet application and creating a session when user login and after some time say 10 min if user is idle, i want to invalidate session and redirect to a jsp page. How to implement it?
I am doing this in web.xml as below
But by this way i am not able to redirect to any jsp page(say Login.jsp).
So when user come back after 10 min and tried to do any action over this application then this through null pointer exception, as i am storing and using some parameter in session.
Servlet 3.0 Specification 7.5 wrote:In the HTTP protocol, there is no explicit termination signal when a client is no
longer active. This means that the only mechanism that can be used to indicate when
a client is no longer active is a time out period.
The default time out period for sessions is defined by the servlet container and can
be obtained via the getMaxInactiveInterval method of the HttpSession interface.
This time out can be changed by the Developer using the setMaxInactiveInterval
method of the HttpSession interface. The time out periods used by these methods
are defined in seconds. By definition, if the time out period for a session is set to -1,
the session will never expire. The session invalidation will not take effect until all
servlets using that session have exited the service method. Once the session
invalidation is initiated, a new request must not be able to see that session.
You can create a filter (that implements the javax.servlet.Filter interface) that checks every request whether the parameter stored in the Session is still available. If not redirect from the Filter to the Login.jsp, else continue with the processing of your request.
The problem with this solution is that you never know when the container will call the destroy() method on a Servlet (with the exception of when tearing down the web-app). It is however not called when a Session expires because the Servlet can service a number of clients at that moment.
Another idea could de implementing a HttpSessionListener which will tell you when a Session is about to be destroyed, but you can only do something with the Session object befored it is removed from memory: there is no possibility to redirect (you also don't know whether the client is still working on your web-app, this you can only tell when he does send in a new Request)
So the logical way is by implementing a Filter in front of your web-app where you will only allow Requests from clients where the Session is not yet expired.