问题描述
如何在会话到期时(自动)在页面上没有任何用户操作的情况下重定向页面。?
How to redirect a page upon session expiry(automatically) with out any user action on the page.?
推荐答案
创建活动检查器,检查每分钟是否发生了任何用户活动(鼠标点击,按键),并向服务器端执行心跳以在用户处于活动状态时保持会话处于活动状态,并在用户未处于活动状态时不执行任何操作。如果30分钟内没有活动(或者在服务器端设置了默认会话超时),则执行重定向。
Create an activity checker which checks every minute if any user activity has taken place (mouseclick, keypress) and performs a heartbeat to the server side to keep the session alive when the user is active and does nothing when the user is not active. When there is no activity for 30 minutes (or whatever default session timeout is been set on server side), then perform a redirect.
这是一个启动示例,几乎没有帮助绑定点击和按键事件并触发ajax请求。
Here's a kickoff example with little help of jQuery to bind click and keypress events and fire ajax request.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$.active = false;
$('body').bind('click keypress', function() { $.active = true; });
checkActivity(1800000, 60000, 0); // timeout = 30 minutes, interval = 1 minute.
});
function checkActivity(timeout, interval, elapsed) {
if ($.active) {
elapsed = 0;
$.active = false;
$.get('heartbeat');
}
if (elapsed < timeout) {
elapsed += interval;
setTimeout(function() {
checkActivity(timeout, interval, elapsed);
}, interval);
} else {
window.location = 'http://example.com/expired'; // Redirect to "session expired" page.
}
}
</script>
创建 Servlet
,监听 / heartbeat
并且基本上只做以下几点:
Create a Servlet
which listens on /heartbeat
and does basically just the following:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
request.getSession();
}
保持会话活着。
这篇关于会话到期时自动重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!