Java 在会话超时前警告用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23930541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:08:57  来源:igfitidea点击:

Warn the user before session timeout

javajavascriptjquerysession

提问by user3509911

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

我在Spring MVC, 中实现了一个 Web 应用程序JSP
默认会话超时定义web.xml为 30 分钟。

if user is idle for 25 mins than I need to show a popup to user with message that Your session is going to be end by 5 min, Please click OK to continue.

如果用户空闲 25 分钟,我需要向用户显示一个弹出窗口,其中包含Your session is going to be end by 5 min, Please click OK to continue.

Do we can achieve this using JavaScript, jqueryor any other approach?

难道我们能做到这一点使用JavaScriptjquery或任何其他的方法呢?

Please suggest.

请建议。

回答by Aminadav Glickshtein

Do you know windows.setTimeout

你知道 windows.setTimeout

http://www.w3schools.com/jsref/met_win_settimeout.asp

http://www.w3schools.com/jsref/met_win_settimeout.asp

This is what you need

这就是你需要的

For example

例如

var resetTime_int;
function resetTimer(){
    if(resetTime_int) window.clearTimeout(resetTime_int)
    resetTime_int=window.setTimeout(function (){
    if(prompt('Your session is going to be end by 5 min, Please click OK to continue'))     
    location.reload()
    }, 1000*60*25)
}

resetTimer()
document.onmousemove=resetTimer
document.onkeyup=resetTimer

1000*60*25 = 25 Minutes.

1000*60*25 = 25 分钟。

回答by flec

You could send a cookie with the remaining time (in milliseconds) on every request. Then you can use setTimeout as suggested but test the value again when the timeout-function is executed. If the value has changed you can reset the timeout. Since the cookie is set for the whole domain it will always be correct even for ajax or other tabs.

您可以在每个请求上发送一个带有剩余时间(以毫秒为单位)的 cookie。然后,您可以按照建议使用 setTimeout,但在执行 timeout-function 时再次测试该值。如果值已更改,您可以重置超时。由于 cookie 是为整个域设置的,因此即使对于 ajax 或其他选项卡,它也始终是正确的。

var cookieName = 'sessionMsg';
var message = '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<ca.length; i++)
    {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
    return "";
}

function setSessionPrompt() {
    var timeout = getCookie(cookieName) - new Date().getTime();
    setTimeout(function(){
        if (new Date().getTime() < getCookie(cookieName)) {
            setSessionPrompt();
        } else {
            if(confirm(message)) {
                // do your action here
            }
        }
    }, timeout);
}

setSessionPrompt();

回答by Nitul

You should use WebSockets to send data from the Web Application to clients browser.

您应该使用 WebSockets 将数据从 Web 应用程序发送到客户端浏览器。

1) calculate the session timeouts at server side. 2) Websocket will send the message about session time out message.

1)计算服务器端的会话超时。2) Websocket 将发送有关会话超时消息的消息。

回答by Mohit

Try this code. Hopefully it will solve your problem. Thanks

试试这个代码。希望它能解决你的问题。谢谢

var cookieName = 'sessionMsg';
var message = '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<ca.length; i++)
    {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
    return "";
}

function setSessionPrompt() {
    var timeout = getCookie(cookieName) - new Date().getTime();
    setTimeout(function(){
        if (new Date().getTime() < getCookie(cookieName)) {
            setSessionPrompt();
        } else {
            if(confirm(message)) {
                // do your action here
            }
        }
    }, timeout);
}

setSessionPrompt();

回答by Md. Kamruzzaman

You can use like follows: I am using that in a jsp page like header.jsp. It works fine for me. I am using spring, jsp and jquery.

你可以像下面这样使用:我在像header.jsp这样的jsp页面中使用它。这对我来说可以。我正在使用 spring、jsp 和 jquery。

javascript:

javascript:

<code>
<script type="text/javascript">
    //var recall = true;
    function loadDialog() { 
            var sessionAlive = ${pageContext.session.maxInactiveInterval};          
            var notifyBefore = 30; // Give client 15 seconds to choose.
            setTimeout(function() {       
                $(function() {
                    $( "#dialog" ).dialog({
                        autoOpen: true,
                        maxWidth:400,
                        maxHeight: 200,
                        width: 400,
                        height: 200,
                        modal: true,
                        open: function(event, ui) {
                            setTimeout(function(){
                                $('#dialog').dialog('close'); 
                            }, notifyBefore * 1000);
                        },
                        buttons: {
                        "Yes": function() {  
                             $.get("/about", function(data,status){
                               // alert("Data: " + data + "\nStatus: " + status);
                              });                             
                            $('#dialog').dialog("close");
                            loadDialog();
                        },
                        "No": function() {  
                            $('#dialog').dialog("close");
                        }
                       },
                       close: function() {}
                    });
                  });
            }, (sessionAlive - notifyBefore) * 1000);
    };

    loadDialog(); 
</script>

HTML Div:

HTML 分区:

<div id="dialog" title="Session Timeout Info" style="display:none">
  <p>
    Your session will be timeout within 30 seconds. Do you want to continue session?  
  </p>
</div> 
</code>

回答by wardanuy

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.htmlas a baseline.

为了通知用户前端的超时,您需要从后端传递此信息。为此,我使用https://www.javaworld.com/article/2073234/tracking-session-expiration-in-browser.html 中的信息作为基准。

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:

在控制器中的每个响应方法中,您需要包含包含会话超时时间以及当前服务器时间的 cookie。由于听起来您已经在 web.xml 中设置了会话超时,因此您可以使用类似于以下内容的内容将 cookie 添加到您的响应中:

@RequestMapping(value="/example", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public ResponseEntity<Object> getExample(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
     addTimeoutCookies(servletRequest, servletResponse);

     //Do actual actions

     return new ResponseEntity<Object>(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:

然后,在前端,您需要检索这些 cookie 的值并将它们与客户端当前时间进行比较,以确定何时通知用户即将到来的会话超时。这是一个简单的代码块,基于此处的其他答案和链接中的文章:

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<ca.length; i++)
    {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
    return "";
}

var serverTime = getCookie(currTimeCookieName);
serverTime = serverTime==null ? null : Math.abs(serverTime);
var offset = (new Date()).getTime() - serverTime;

function getTimeToWarning() {
    var expireTime = getCookie(expireTimeCookieName);
    return expireTime + offset - currTime - warningTime;
}

function checkForTimeout() {
    var timeUntilWarning = getTimeToWarning();

    setTimeout(function(){
        if (getTimeToWarning() > 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();

回答by Srimoyee Sen

You can use the following plugin - Jtimeout jquery pluginWorks perfectly and is configurable too. The doc is pretty clear

您可以使用以下插件 - Jtimeout jquery 插件完美运行并且也可配置。文档很清楚