简体   繁体   中英

How to logout automatically after session timeout on server in java web application

I have a small web application with simple requirement that, I have a servlet and few JSP pages in my application. When ever we give request to sevrlet it starts session on server with session timeout 1minute, then it displays one JSP page. After session timeout on server I want to automatically display sign out JSP page in the browser how can we achieve this.

To add to Jhash

  1. You have to have a timer javascript function on every jsp of your application (you can keep it in a .js file and include it)
  2. Your session on the server can be about 30 minutes and your javascript timer can be around 2 to 5 minutes because even if a cached html page is shown, it would find out the situation within 2 minutes
  3. Hope you are not relying on this for securing the application. You should still check on serverside that the user session is valid before letting the user use your application (the javascript should be only for convenience)

Edit: Example of guessing timeout in JS and then navigating the user out:

var lastActiveTimeMs = new Date().getTime(); //This is set to current time on page load
var SESSION_TIMEOUT_MILLIS = 35*60*1000; //35 mins in milliseconds
var CHECK_TIME_MILLIS = 60*1000; //1 mins in milliseconds

setTimeout(fnCheckTimeout, CHECK_TIME_MILLIS); //Check the timeout once in a minute
function fnCheckTimeout(){
  var curMs = new Date().getTime();
  if( (curMs-lastActiveTimeMs)>SESSION_TIMEOUT_MILLIS ){
    window.location.href = 'signout.html';
  }
}

//Keep updating lastActiveTime every time you do an Ajax call. 
//Because server will keep extending the session for every page load or ajax call from client

For this you need to use javascript in your jsp page. For example if your session timeout is 2 minutes on server, in JSP page also you need to create a timer with same time using javascript, after javascript timer timeout happens, you just need to refresh the page by using same javascript code. so when you refresh the page session timeout happened already on server so you can check for session on server and if session is expired redirect control to the page you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM