简体   繁体   中英

How to dynamically calculate session timeout?

Hi I am trying to calculate from my /logout servlet the session timeout. I have defined a certain amount of time before timeout as timeout

My doPost method is here:

   import java.io.IOException;
   import java.util.logging.Level;
   import java.util.logging.Logger;

   import javax.servlet.ServletException;
   import javax.servlet.annotation.WebServlet;
   import javax.servlet.http.HttpServlet;
   import javax.servlet.http.HttpServletRequest;
   import javax.servlet.http.HttpServletResponse;
   import javax.ws.rs.core.MediaType;
   import com.sun.jersey.api.client.ClientResponse.Status;

   protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    long timePassed = 0;
    long timeout = 60;

    timePassed = (System.currentTimeMillis() - request.getSession().getLastAccessedTime())/1000;
    System.out.println(timePassed);

    response.setStatus(Status.OK.getStatusCode());
    response.getWriter().write("[{\"timePassed\": \""+ timePassed + "\", \"limit\": \""+ timeout + "\"}]");
    response.setContentType(MediaType.APPLICATION_JSON); 

    if(timePassed >= timeout){
        doGet(request, response);
    }

}

I hit this method every second with an ajax call. The ajax call works fine. GUI works fine because I am getting the data in the front end. BUT timePassed stays at 0. How do I get it to calculate the time that the user has spent idle?

Why don't you use javascript to detect clicks or mouse movements?

jQuery or native Javascript can accomplish what you need...

[Edit]

If certains calls to the backend release the idle time, you can monitor those with Javascript :-)

You are getting timePassed stays as 0 because, I guess you are directly calling the servlet.

Do one thing, Add some debug points at the below code and restart your server in debug mode. when the debugger reaches the debug point wait for 5-6 seconds and suspend the debugging by pressing press F8. you will definitely get some value for timePassed other than 0.

timePassed = (System.currentTimeMillis() - request.getSession().getLastAccessedTime())/1000;
System.out.println(timePassed);

One more trick, instead of debug. when you get the timePassed value as zero then wait for few seconds and refresh the page(resubmit the form). you will get the output as below:

会话超时

This is because, when you first redirect to the servlet, the session time lapsed is 0, Since the session is just started. and when a new request is made in same session the time lapsed will increase.

Hope this helps you.

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