注销Servlet无法正常工作

时间:2014-05-12 12:09:31

标签: java-ee servlets

我已经为logout servlet编写了这段代码,但是当我点击后退按钮时,一切正常。建议

public class LogOut extends HttpServlet {


    private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
System.out.println("logging out");

HttpSession session1=request.getSession();  

session1.invalidate();  

out.print("You are successfully logged out!");  
RequestDispatcher rd= request.getRequestDispatcher("/Logout.jsp");
rd.forward(request, response);

out.close();  


}
}

3 个答案:

答案 0 :(得分:0)

虽然没有完美的方法(用户可以禁用javascript),但我们可以使用history.forward()方法强制用户退回到下一页。但是由于浏览器不是每次都调用onload方法而且还有其他问题我们必须修改我们的代码

   <html>
    <head>
    <title>Page One</title>
    <script>
    function backButtonOverride()
    {
      setTimeout("backButtonOverrideBody()", 1);
    }

    function backButtonOverrideBody()
    {

      try {
        history.forward();
      } catch (e) {

      }

      setTimeout("backButtonOverrideBody()", 500);
    }
    </script>
    </head>
    <body onLoad="backButtonOverride()">
    <h1>Page One</h1>
    <a href="page2.html">Move to Page Two</a>
    </body>
    </html>

我建议不要在注销页面之前的页面中实现此代码,而是在注销页面本身实现此代码,并添加javascript代码以将用户从注销页面重定向到“登录页面”,只是为了增加安全性,使用: -

window.location = url;

答案 1 :(得分:0)

在logut servelt

你需要这样做

response.addHeader("Cache-Control", "no-cache,no-store,private,must-revalidate,max-stale=0,post-check=0,pre-check=0"); 
response.addHeader("Pragma", "no-cache"); 
response.addDateHeader ("Expires", 0);

如果您使用的是Cookie,则需要清除它们

/**
         * Invalidate all cookies by, for each cookie received, 
         * overwriting value and instructing browser to deletes it
         */
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                cookie.setValue("-");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }

在您的Logout.jsp中,您可以在头标记中添加这些

<head>
<meta http-equiv="Cache-Control" content="no-cache,no-store,private,must-revalidate,max-stale=0,post-check=0,pre-check=0" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
</head>

答案 2 :(得分:0)

Session invalidation is enough for a perfect logout servlet.In order to made logout   working properly we want to add a concept of validating authentication.

HttpSession session = request.getSession(true);

session.invalidate();

每次用户登录时创建一个Auth对象。包括id,username..etc。然后检查    authObj在servlet内部的每个操作开始。会话失效后    如果你尝试做任何操作,你就不会得到那个authObj。因为我们没有用户名    (例如:)我们已经保持在会话中。用户名不可用的原因是我们已经完成了会话无效。所以我们无法进行任何我们需要登录的操作。然后只是添加如下消息:

PrintWriter out = response.getWriter();

out.println(&#34; SESSION FAILED!&#34;);