兩件事情
第一:如果有可能,總是喜歡客戶端重定向到這是/LoginController
而調度請求的目標頁面。
由於某些容器(如tomcat)存在一些bug,導致目標頁面將作爲ASCII數據進行響應(只是嘗試打印一些utf-8數據並查看它)。
除了這項技術之外,還會使您的業務和代碼變得複雜,如果您問我,將難以維護。第二:我建議你不要驗證一個會話的nullify
狀態,因爲如果你在其他地方創建它,這個頁面會將客戶端視爲已登錄的人,所以你最好將某個屬性設置爲一個會話,也許像此:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession ses=request.getSession();//let it be always created for this
boolean logged=ses.getAttribute("logged")==Boolean.TRUE;
//Redirects to LoginController.java if there is no session
if(logged){
response.sendRedirect("/login-controller");
return;//you cannot do anything with the request/response once it's redirected or forwarded.
}else{
PrintWriter out = response.getWriter();
out.print("Logout to login again!");
}
}
後來與登錄表單設置logged
屬性作爲true
,其指示用戶已經成功登錄。
回到您的問題:
如果您堅持調試存在的代碼,您需要檢查客戶端可能調用哪些可能創建會話的所有路徑(servlet,stuffs)。如果你懶惰,你可能有一個會話監聽器,並且只需要一個斷點或者顯示堆棧來查看哪個組件創建會話,如下所示。
public class session_listener implements HttpSessionListener,ServletContextListener {
public session_listener() {}
@Override public void sessionCreated(HttpSessionEvent se) {
//have a break-point and check stack to see who just created the session
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
//have a break-point and check stack to see who just destroyed the session
}
@Override public void contextInitialized(ServletContextEvent sce){}
@Override public void contextDestroyed(ServletContextEvent sce) {}
}
而且簡單的註冊聽衆中web.xml
<web-app ... >
...
<listener>
<listener-class>arpit.tomar.session_listener</listener-class>
</listener>
...
</web-app>
記住無效的會議不會使會話對象爲空以相同的要求!沒有。響應必須已成功由客戶端獲取,通知客戶端在此之後不發送會話cookie(如果是cookie),所以當您的服務器併發工作時,您可能一次獲得n個請求,這些請求都指示同一個會話。
是否有任何過濾器或在'processRequest'之前被調用的東西? –
不,netbeans在默認servlet中的唯一更改是processRequest方法中的更改。 –
你見過這個鏈接嗎?認爲它可能有助於http://stackoverflow.com/questions/24677949/why-session-is-not-null-after-session-invalidate-in-java – NaNey