2017-04-11 55 views
0

我有一個logout.jsp頁面,這是用來無效會話,這裏不是取消設置會話可以是它的內容:在Java Servlet的

session.invalidate(); 
response.sendRedirect("login.jsp"); 

在我profile.jsp頁我要檢查是否會話變量設置與否,並取決於允許用戶瀏覽網頁或重定向到登錄頁面(如果會話變量未設置)

if(request.getSession(false)==null){ 
    response.sendRedirect("login.jsp"); 
} 

但問題是,這是不工作作爲即使在沒有用戶登錄的情況下,也可以直接從地址欄打開profile.jsp頁面,該頁面將以o打開ut重定向到登錄頁面。進一步在打印request.getSession(false)我得到輸出[email protected]。我不知道這是什麼,也沒有在互聯網上發現它。那麼如何解決這個問題。

編輯:

類「用戶」,其對象我使用的會話變量實現了系列化,所以,可以說是我所面臨的問題的原因。

我沒有被允許評論,所以我在這裏提到它。 我使用鉻接受cookie ....進一步我在Microsoft邊緣嘗試相同,但它仍然是相同的

+0

一個JSP會自動創建一個會話,除非您告訴它不要創建一個會話。通常我們在會話中放置一個屬性並檢查是否設置了該屬性。 – rickz

+0

是的,我也嘗試過:'if(session.getAttribute(「user」)== null){ \t response.sendRedirect(「login.jsp」);} System.out.println(session.getAttribute 「user」));'這裏用戶是會話變量屬性,控制檯輸出是'mypack.user @ 1ad20a7',其中mypack是包的名稱我有一個'user'命名的類。我使用的對象是會話變量 – Sourajit

+0

這不是重定向 – Sourajit

回答

0

我假設你已經創建了登錄和註銷的servlet,然後從相應的servlet,你可以重定向頁面: 這可能是您的登錄servlet代碼:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    String email = request.getParameter("email"); 
    String password = request.getParameter("password"); 
    HttpSession session = request.getSession(); 
    session.setAttribute("userName", email); 
    session.setAttribute("password", password); 
    getServletContext().getRequestDispatcher("/profile.jsp").forward(request, 
    response); 
    } 

這可能是你的profile.jsp網頁代碼來檢查會話:

<% 
if(!(request.getSession(true).getAttribute("userName").toString()).isEmpty()){ 
    String firstName = (String)request.getAttribute("firstName"); 
String lastName = (String)request.getAttribute("lastName"); 
}else{%> 
<jsp:forward page = "Login.jsp" /> 
<% }%> 

從登出頁面你可以發送請求lo goutservlet。而且,這可能是您的logoutservlet代碼:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 
    HttpSession session = request.getSession(); 
    session.invalidate(); 
    out.println("Logout Successful"); 
    out.println("Username : "+session.getAttribute("userName")); 
    out.println("Password : "+session.getAttribute("password")); 

} 

然後當我正在從會話我得到空值對於這些領域的憑據後。

+0

'<%= request。getSession(true).getAttribute(「userName」)。toString()。isEmpty()%>'返回false ...我嘗試了上面的方法,並在我的註銷頁面中request.getSession(false)'返回null,但是在打開profile.jsp頁面(沒有登錄)它返回true ...如果你想看到我的任何特定的文件,你可以提到我會在這裏添加它。 – Sourajit