2015-07-22 87 views
0

我正在開發一個Web應用程序使用jspservlet。在我的應用程序有一個註銷部分,在我使用下面的代碼:會議未註銷清除

public class logout extends HttpServlet { 

    public void service(HttpServletRequest rq, HttpServletResponse rs) throws IOException, ServletException { 
     try { 
      HttpSession ss = rq.getSession(false); 
      if (ss.getAttribute("uid") == null) { 
       rs.sendRedirect("/"); 
      } 

      rs.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); 
      rs.addHeader("Cache-Control", "post-check=0, pre-check=0"); 
      rs.setHeader("Pragma", "no-cache"); 
      rs.setDateHeader("Expires", 0); 
      HttpSession session = rq.getSession(false); 
      session.setAttribute("uid", null); 
      session.invalidate(); 
      rs.sendRedirect("/"); 
     } catch (Exception exp) { 
      // rs.sendRedirect("/"); 
      RequestDispatcher dd = rq.getRequestDispatcher("/"); 
      dd.forward(rq, rs); 
     } 

    } 
} 

在瀏覽器中,如果我們連續使用,每週想不清除歷史,那麼如果我們登錄並點擊註銷,它將註銷重定向到主頁,但會話仍然存在。 會話在註銷時未被清除。

發生了什麼問題?我的代碼中是否還需要其他更改?

回答

0

不知道問題是什麼,但有一些建議。

  1. 不需要創建兩個HttpSession對象(ss和會話),只嘗試使用一個。
  2. 嘗試刪除「uid」屬性,而不是將其設置爲空。
  3. 在調用它的invalidate()方法之前,嘗試檢查HttpSession是否爲null。

所以最終的代碼會,

public class logout extends HttpServlet { 

    public void service(HttpServletRequest rq, HttpServletResponse rs) throws IOException, ServletException { 
     try { 
      rs.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); 
      rs.addHeader("Cache-Control", "post-check=0, pre-check=0"); 
      rs.setHeader("Pragma", "no-cache"); 
      rs.setDateHeader("Expires", 0); 
      HttpSession ss = rq.getSession(false); 
      if (ss.getAttribute("uid") == null) { 
       rs.sendRedirect("/"); 
      } 

      ss.removeAttribute("uid"); 
      if (ss != null) { 
       ss.invalidate(); 
      } 
      rs.sendRedirect("/"); 
     } catch (Exception exp) { 
      // rs.sendRedirect("/"); 
      RequestDispatcher dd = rq.getRequestDispatcher("/"); 
      dd.forward(rq, rs); 
     } 

    } 
} 
+0

我覺得在這一行有一些問題HttpSession ss = rq.getSession(false);正如上面提到的代碼! – Santhucool

+0

你有沒有例外? – Niranjan

+0

NOPE !!我沒有得到任何 – Santhucool

0

我認爲你是不正確的用戶會話管理到應用程序中。 我建議使用自定義過濾器來防止每個頁面的瀏覽器catche。

rs.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); 
rs.addHeader("Cache-Control", "post-check=0, pre-check=0"); 
rs.setHeader("Pragma", "no-cache"); 
rs.setDateHeader("Expires", 0); 

打算在此之後,你需要檢查會話有效期爲通過過濾器每一個請求或檢查會話的每個頁面(視圖)和有效的,如果會話無效然後重定向到索引頁面。

並對Logout控制器進行一些修正。

public void service(HttpServletRequest rq, HttpServletResponse rs) throws IOException, ServletException { 
    try { 
     HttpSession session = rq.getSession(false); 
     session.removeAttribute("uid"); 
     session.invalidate(); 
     rs.sendRedirect("/"); 
    } catch (Exception exp) { 
     RequestDispatcher dd = rq.getRequestDispatcher("/"); 
     dd.forward(rq, rs); 
    } 

}