th3r1singking
th3r1singking

Reputation: 131

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?

Upvotes: 0

Views: 1501

Answers (2)

Rohit Gaikwad
Rohit Gaikwad

Reputation: 3904

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:

Session TimeOut

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.

Upvotes: 1

Bert Persyn
Bert Persyn

Reputation: 411

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 :-)

Upvotes: 1

Related Questions