JSP登录页面会话超时

时间:2013-12-04 18:53:45

标签: java spring jsp servlets mybatis

我已经为酒店管理员的模拟创建了一个登录页面。现在我想为它添加会话时间功能。换句话说,假设用户离开计算机(他仍然登录管理网页)大约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");
}
}

2 个答案:

答案 0 :(得分:5)

使用身份验证过滤器检查每个请求中的会话

 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>

检查here

答案 1 :(得分:1)

验证凭据后,为userid设置会话变量,并设置会话到期时间:

 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。