2014-04-08 69 views
2

考慮的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); 
} 

我該如何解決?

非常感謝

+0

,因爲你是無效會話 –

+0

這不是還活着後,轉發請求到該JSP。你有一個新的會議。 – EJP

+1

因爲它在WEB-INF下,所以沒有達到error404.jsp的代碼。不要將JSP放在WEB-INF下。 –

回答

1

基本上,if(session != null){沒什麼意思在這裏。你應該閱讀從會話屬性,檢查其是否爲空:

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

因爲每次訪問JSP都會創建一個新會話。要禁用此屬性將這個指令:

<%@ page session="false" %> 
相關問題