Warn the user before session timeout

前端 未结 7 2323
感动是毒
感动是毒 2020-12-09 18:08

I have a web application implemented in Spring MVC, JSP.
Default session timeout is defined in web.xml is 30 min.

if use

7条回答
  •  一向
    一向 (楼主)
    2020-12-09 18:37

    In order to notify the user about the timeouts on the frontend, you need to pass this information from your backend. To accomplish this, I used the info in https://www.javaworld.com/article/2073234/tracking-session-expiration-in-browser.html as a baseline.

    In each Response method in your Controller you need to include cookies containing the session timeout time, as well as the current server time. Since it sounds like you've already set the session-timeout in your web.xml, you can add the cookies to your response with something similar to:

    @RequestMapping(value="/example", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public ResponseEntity getExample(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
         addTimeoutCookies(servletRequest, servletResponse);
    
         //Do actual actions
    
         return new ResponseEntity(HttpStatus.OK)
    }
    
    private void addTimeoutCookies(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
    
        long currTime = System.currentTimeMillis();
        long expiryTime = currTime + servletRequest.getSession().getMaxInactiveInterval() * 1000;
    
        Cookie serverTimeCookie = new Cookie("serverTime", "" + currTime);
        serverTimeCookie.setPath("/");
        servletResponse.addCookie(serverTimeCookie);
    
        Cookie expiryCookie = new Cookie("sessionExpiry", "" + expiryTime);
        expiryCookie.setPath("/");
        servletResponse.addCookie(expiryCookie);
    }
    
    
    

    Then, on the frontend, you need to retrieve the values of these cookies and compare them against the client current time to determine when to notify the user about the upcoming session timeout. Here's a simple code block to do this, based on the other answers here and the article at the link:

    var currTimeCookieName = 'serverTime';
    var expireTimeCookieName = 'sessionExpiry';
    var offset;
    var warningTime = 5 * 60 * 1000;
    var timeoutWarningMessage = 'Your session is going to be end by 5 min, Please click OK to continue';
    
    function getCookie(name)
    {
        var name = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i 0) {
                checkForTimeout();
            } else {
    
                if(confirm(timeoutWarningMessage)) {
                    //TODO do a backend call or other action to extend the session here
    
                    setTimeout(function() {
                        checkForTimeout();
                    }, 1 * 60 * 1000);
                }
            }
        }, timeUntilWarning);
    }
    
    checkForTimeout();
    

    提交回复
    热议问题