[英]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.