Search code examples
javaservletsweb-applicationshttpsession

HttpSession using servlets


I am trying to create a http session of 5 seconds. Here is the code

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    HttpSession sess=req.getSession(true);;
    String fname=req.getParameter("fname");
    String lname=req.getParameter("lname");
    PrintWriter pw=resp.getWriter();
    pw.println("Hello"+" "+fname+" "+lname);
    long stime=sess.getCreationTime();
    long ltime=sess.getLastAccessedTime();
    if((ltime-stime)>5000)
    {
        pw.println("Session Expires");
        sess.invalidate();
    }
    pw.close();
}

The problem is when I reload the page for the 1st time after 5 seconds the session does not expire but after reloading the page 2nd time the session expires. Plz guide....


Solution

  • You can set the session expiry time:

    // set 5 seconds
    // default is 1800 seconds (30 minutes)
    sess.setMaxInactiveInterval(5);
    

    And after this elapsed time the session will expire automatically.