2017-08-23 40 views
0

我正在開發一個大學項目,我會嘗試用一個小例子來解釋我的問題。 下面有3個jsp頁面(的index.jsptest.jsp的logged.jsp),我想的是,如果用戶通過輸入URL http://localhost:8080/sessionTest/logged.jsp嘗試直接訪問logged.jsp那麼他將重定向到index.jspjsp項目中的會話管理

的index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>JSP Page</title> 
    </head> 
    <body> 
     <form action ="test.jsp" method="post"> 
      enter user id :<input type="text" name="user"> 
      Enter password:<input type="password" name="pass"> 
      <input type="submit" value="submit"> 
     </form> 
    </body> 
</html> 

test.jsp的

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>JSP Page</title> 
    </head> 
    <body> 
     <% 
    String user= request.getParameter("user"); 
    String pass= request.getParameter("pass"); 
    if(user.equals("snow")&& pass.equals("123")) 
    { 
     session.setAttribute("user", user); 
     RequestDispatcher r = request.getRequestDispatcher("logged.jsp"); 
     r.forward(request, response); 
    } 
    else { 
     out.println("wrong pass or id"); 
    } 
      %> 
    </body> 
</html> 

logged.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>JSP Page</title> 
    </head> 
    <body> 
     <% session = request.getSession(false); 
      if(session==null) 
      { 
       response.sendRedirect("index.jsp"); 
      } 
      else{ 
       out.println("welcome its old session"); 
      } 
     %> 
    </body> 
</html> 

請幫助我做一些代碼,並解釋它是如何工作

+0

錯誤的做法。您需要檢查會話中的會話屬性(如userid)以檢查用戶是否已登錄,並且需要在每個頁面中執行此操作,並且如果不符合該條件,則每個頁面都會重定向到登錄屏幕。您可以通過將此代碼放在每個頁面的頂部或通過使用servlet過濾器來完成此操作。但是,如果只檢查登錄頁面而不檢索索引和其他需要保護的頁面,則可以直接訪問index.jsp並繞過假定的安全性。 – developerwjk

+0

你能解釋一下這個代碼@developerwjk。 – BlindCoder

+0

其實很像Maulik Bhatt的回答,除了相反。在每一頁應該被保護的開始處:'if(session.getAttribute(「username」)== null){response.sendRedirect(「login_form.jsp」);返回; }'這樣如果用戶沒有登錄,他們會被重定向到登錄表單。 – developerwjk

回答

0

試試這個可能是它可以幫助你:

<% 
HttpSession session = request.getSession(); 

if(null!=session.getAttribute("username")){ 
    out.write("username is "+session.getAttribute("username").toString()); 

    } 
else{ 
    response.sendRedirect("/index.jsp"); 
    } 
%>