Reputation: 21
I have using jsp technology in my project.I want to do session tracking in my login form. After logout when i press back button it should be show session is expired.Please help me.
Upvotes: 1
Views: 5200
Reputation: 47183
First, session creation and destruction:
Use HttpSessionListener.
Implement sessionCreated(HttpSessionEvent se)
with an output telling you that a session has been created.
Implement sessionDestroyed(HttpSessionEvent se)
with an output telling you that a session has been destroyed. That is, a user has logged off, or user's session has expired.
Now, the middle part. Use a filter, with a corresponding web.xml
entry of *.jsp
for that filter. Inside of your filter, use doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
. Cast ServletRequest
to HttpServletRequest
. Using that request you'll have many methods that you can use for session tracking. User's credentials, visiting URL, basically everything that could be of interest.
Upvotes: 0
Reputation: 1108712
You don't need to do it manually. The servletcontainer will do it for you. You can access the tracked session by HttpServletRequest#getSession()
. All you need to do is to put the logged-in user as a session attribute.
request.getSession().setAttribute("user", user);
Let the rest of your code intercept on that. You usually use a Filter
for this.
if (request.getSession().getAttribute("user") == null) {
// Not logged in. Redirect to login page.
response.sendRedirect("login.jsp");
} else {
// Logged in. Just continue request.
chain.doFilter(request, response);
}
When you invoke the logout, just remove the user from the session.
request.getSession().removeAttribute("user");
The servletcontainer will manage the session expiration as well. When it expires, then the HttpSession
will simply be trashed, including all of its attribtues.
As to the back button question, just instruct the client to not cache the response so that it's forced to fire a brand new request which would then be passed through the Filter
. This client instruction needs to happen by setting the response headers accordingly. That could be done in a Filter
as well.
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
Upvotes: 1