我已经创建了一个模拟酒店管理员的登录页面。现在我想给它添加 session 时间功能。换句话说,假设用户离开计算机(他仍然登录到管理网页)大约 10 分钟。然后当他回来的时候,我想结束当前 session ,然后重定向到登录页面(这样更安全,他的个人信息永远不会丢失!)。
我该如何实现?
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");
}
}
最佳答案
使用身份验证过滤器检查每个请求中的 session
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);
}
这将为每个请求检查来自 session 的登录用户名,如果它为空或 session 已过期,它将重定向到登录页面。
在 web.xml 中添加这个
<session-config>
<session-timeout>5</session-timeout>
</session-config>
查一下here .
关于java - JSP 登录页面 session 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20383513/