Redirecting automatically upon session expiry [closed]
How to redirect a page upon session expiry(automatically) with out any user action on the page.?
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.
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>
Create a Servlet
which listens on /heartbeat
and does basically just the following:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
request.getSession();
}
to keep the session alive.
精彩评论