当用户在指定时间内不活动时将用户重定向到特定页面

Redirect user to specific page when user is inactive for a specified time

我想对我的 servlet 进行编程,以在用户处于非活动状态 10 分钟后阻止会话而不关闭并将用户重定向到页面 sessionlocked.jsp

我测试了这段代码,但它不起作用。

session.setMaxInactiveInterval(10*60);
if (request.getSession(false) == null) {
    response.sendRedirect(url);
}

我怎样才能做到这一点?

documentation;

setMaxInactiveInterval(int interval)

Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

所以setMaxInactiveInterval方法不符合您的需求,它使会话无效。

要向用户显示锁定的页面,您有两种选择;

第一;

Use filters to check session time and if time is over redirect to lockedpage otherwise reset time.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpSession session = ((HttpServletRequest) request).getSession(false);
    if (session == null) {
        // ((HttpServletRequest) request).getSession(true);
        // redirect to logout or anywhere you want, to create a session
        return;
    }
    // Check if filter also work for sessionlocked.jsp
    if (((HttpServletRequest) request).getRequestURL().toString().contains("sessionlocked")) {
        chain.doFilter(request, response); // no need to check sessionlocked
        return;
    }
    long lastAccessTime = session.getLastAccessedTime();
    long tenMinuteAsMilisecond = 10 * 60 * 1000;
    if (lastAccessTime + tenMinuteAsMilisecond > (new Date()).getTime()) {
        chain.doFilter(request, response); // session still not locked
    } else {
        ((HttpServletResponse) response).sendRedirect("sessionlocked.jsp");
    }
}

第二次(除了第一次,因为第一次尝试在服务器端控制);

Use javascript to count down and when time is over, redirect user to the locked page.

 window.onload = function() {
        setInterval(function() {
            window.location.replace("/sessionlocked.jsp");
              }, 600000);
    }

如果只需要servlet; (当用户与 servlet 交互时)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    if (session == null) {
        request.getSession(true);
        // redirect to logout or anywhere you want, to create a session
        return;
    }
    long lastAccessTime = session.getLastAccessedTime();
    long tenMinuteAsMilisecond = 10 * 1000;// to test lock time set to 10 seconds
    if (lastAccessTime + tenMinuteAsMilisecond > (new Date()).getTime()) {
        response.getOutputStream().print("Session not locked" + i++);
        // TODO for not locked code
    } else {
        response.getOutputStream().print("Session locked");
         //redirect to sessionlocked.jsp
    }
}

Servlet输出(锁​​定时间设置为10秒);