开发者

how to implement session tracking for jsp pages

开发者 https://www.devze.com 2023-01-23 20:53 出处:网络
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

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消