Kill session and redirect to login page on click of logout button

后端 未结 3 823
我寻月下人不归
我寻月下人不归 2021-02-06 02:05

I have the following code in JSP:

<%
    if(session.getAttribute(\"Username\") == null || session.getAttribute(\"Username\") == \"_INVALID_\")
    {
        r         


        
相关标签:
3条回答
  • 2021-02-06 02:14

    You should take a look at the invalidate() method of HttpSession. The session can be retrieved via HttpServletRequest getSession() method.

    You should also take a look at Expires, Cache-Control, Pragma http headers, as in: Prevent user from going back to the previous secured page after logout .

    0 讨论(0)
  • 2021-02-06 02:18

    try this to kill session

    HttpSession newsession = request.getSession(false);
        if (newsession != null) 
        {
             newsession.invalidate();
    
        }
    
       response.sendRedirect("../index.jsp");
    
    0 讨论(0)
  • 2021-02-06 02:31

    In order to kill the current session, you basically need to call HttpSession#invalidate() and perform a redirect to the login or main page. This code is supposed to be placed in doPost() method of a servlet which is invoked by a POST request.

    E.g.

    <form action="${pageContext.request.contextPath}/logout" method="post">
        <input type="submit" value="Logout" />
    </form>
    

    with

    @WebServlet("/logout")
    public class LogoutServlet extends HttpServlet {
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.getSession().invalidate();
            response.sendRedirect(request.getContextPath() + "/LoginPage.html");
        }
    
    }
    

    Unrelated to the concrete problem, your username checking code is not at the right place. You shouldn't be copypasting the same code over every single JSP page. You should be performing this job in a single place in a servlet filter. Java code in JSP files should be avoided as much as possible.

    Further, there's another potential problem when the enduser uses the browser's back button to navigate back in history. By default, the browser will cache all responses and thus the back button might display the page from the browser cache instead of requesting a brand new straight from the server. In order to fix this, see this related question Prevent user from seeing previously visited secured page after logout

    Last but not least, you've there some quite strange HTML. Buttons with onClick to navigate? How user and SEO unfriendly. Use normal <a> links instead. For the button look'n'feel, throw in some CSS.

    0 讨论(0)
提交回复
热议问题