会话无效后,它还活着,为什么?

时间:2014-04-08 22:34:46

标签: java jsp http session servlets

考虑servlet:

package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LogoutServlet
 */
@WebServlet("/loggingOut")
public class LogoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException 
    {
        // Get the session
        HttpSession session = request.getSession(false);

        if(session != null){
            System.out.println("Here ...");
            session.invalidate();
            // forwards to the page logout.jsp
            request.getRequestDispatcher("/WEB-INF/results/logoutResult.jsp").forward(request, response);
            // response.sendRedirect("./WEB-INF/results/logoutResult.jsp");

        }

        else
        {
            System.out.println("There ...");
            // response.sendRedirect("error404.jsp");
            request.getRequestDispatcher("./WEB-INF/results/error404.jsp").forward(request, response);
        }


    }

}

在我使会话无效并移至logoutResult.jsp之后,如果我再次到达上述servlet,则会话仍处于“活动状态”,并且我没有达到error404.jsp的代码,即:

else
{
    System.out.println("There ...");
    // response.sendRedirect("error404.jsp");
    request.getRequestDispatcher("./WEB-INF/results/error404.jsp").forward(request, response);
}

我该如何解决?

非常感谢

2 个答案:

答案 0 :(得分:3)

因为每次访问JSP时都会创建一个新会话。要禁用此属性,请输入以下指令:

<%@ page session="false" %>

答案 1 :(得分:1)

基本上,if(session != null){在这里没有任何意义。您应该从会话中读取一个属性并将其检查为null:

   String username = (String)session.getAttribute("username");
   if(username!=null)
   {
      //user is logged in
   }
   else
   {
     //user is not logged in
   }