[英]JSP login page session timeout
我已經為模擬酒店管理員創建了一個登錄頁面。 現在,我想為其添加會話時間功能。 換句話說,假設用戶離開計算機(他仍然登錄到管理網頁)大約10分鍾左右。 然后,當他回來時,我想結束當前會話,然后重定向到登錄頁面(這更加安全,他的個人信息將永遠不會丟失!)。
我如何做到這一點?
public class LoginServlet extends SpringInjectedServlet {
@Autowired
private LoginService loginService;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String id = req.getParameter("id");
String password = req.getParameter("password");
String error = null;
//code for checking correct input
}
// mock
private boolean check(String id, String password) {
return loginService.authenticate(id, password);
}
@Override
public void init() throws ServletException {
System.out.println("LoginServlet");
}
}
使用身份驗證過濾器在每個請求中檢查會話,例如
HttpSession session = request.getSession();
if (session == null || session.getAttribute("username") == null) {
// Forward the control to login.jsp if authentication fails or session expires
request.getRequestDispatcher("/login.jsp").forward(request,
response);
}
如果會話的null或會話過期,它將為每個請求從會話中檢查登錄用戶名,它將重定向到登錄頁面。
在web.xml中添加
<session-config>
<session-timeout>5</session-timeout>
</session-config>
在這里檢查。
驗證憑據后,為用戶標識設置一個會話變量,並設置會話到期時間:
session.setMaxInactiveInterval(600); //600 secs = 10 mins
session.setAttribute("userid", userid);
然后,在所有JSP和所有servlet的頂部,執行以下操作:
String userid = (String)session.getAttribute("userid");
if(userid==null)
{
response.sendRedirect("login.jsp");
return; //the return is important; forces redirect to go now
}
經過10分鍾后,只有在用戶單擊鏈接,刷新或以某種方式轉到另一個頁面時,這才會將用戶重定向到登錄頁面。 如果他們只是讓頁面坐在那兒保持打開狀態,則仍會顯示。 要進行更改,您必須以某種方式涉及Javascript。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.