Friday, February 13, 2015

How to get/calculate the remaining time for session time out

In Servlet API there is no straight forward method to get the remaining active time of the session. But you can use below two methods provided in HttpSession to calculate this time.

HttpSession.getLastAccessTime() - This method returns the time(in milliseconds) that the client associated with this session sent the last request to the server.
HttpSession.getMaxInactiveInterval() - This is the configured session time out period.

In your servlet you can calculate remaining time as below.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
long now = new Date().getTime();
long lastAccessed = session.getLastAccessedTime();
long timeoutPeriod = session.getMaxInactiveInterval();
long remainingTime = ((timeoutPeriod * 1000) - (now - lastAccessed))/1000;
System.out.println("Remaining time is " + remainingTime + " seconds");
}

Note that if you are using JSF, you can get the associated session as below.
FacesContext ctx = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) ctx.getExternalContext().getSession(false);

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.
    Data Science Training in Chennai
    Data Science course in anna nagar
    Data Science course in chennai
    Data science course in Bangalore
    Data Science course in marathahalli

    ReplyDelete