send heartbeart by calling a jsp doesn't keep session alive

3.5k views Asked by At

I want to keep session alive when I open web page on browser even if I doesn't touch it for a long time, this is how I try to do:

  1. on server side (tomcat), session timeout set to 8 mins.
  2. main jsp generates a html. In this html, I use timer & ajax to call heartbeat.jsp every 3 mins & also pass the initial session id's value to it.
  3. In heartbeat.jsp, I dump session.getId()'s value & initial session id.

[timeline of execution result]:

  • 10:00 I open page -- main jsp program generates client html
  • 10:03 heartbeat.jsp called -- session.getId() = initial session id
  • 10:06 heartbeat.jsp called -- session.getId() = initial session id
  • 10:09 heartbeat.jsp called -- session.getId() <> initial session id

last access time of inital session id is at 10:06, so timeout time of initial session id is supposed at 10:14. But why at 10:09, session.getId() get another new id?

It seems first 2 calls didn't reset intial session's timeout counter on server side. I test this both in IE and Firefox, they have same result

How can I keep session alive for good?

[the main jsp code seg]:

<script type="text/javascript" src="/fp/js/prototype.js"></script>
<script type="text/javascript" src="/fp/js/jquery.min.js"></script>
<script type="text/javascript" src="/fp/js/jquery.roundabout.min.js"></script>
<script type="text/javascript">
  function heartbeats(sid) {
    var url = '/test/heartbeat.jsp' + '?rn=' + Math.random() +'&mysid='+sid;
    var myAjax = new Ajax.Request(url,{
      method: 'get',
      onFailure:  function(request) {
        alert("connect problem, can't do heartbeat!");
      },
      onSuccess: function(response) {
        if (response.responseText.indexOf("timeout") != -1) {
          alert("original session is expired");
        }
      }
    });
  }
  function init_heartbeat(sid) {
    new PeriodicalExecuter(function(startHeart){heartbeats(sid);}, 60*3);
  }
  init_heartbeat("<%=session.getId()%>");
</script>

[heartbeat.jsp code seg]:

  String server_sid = (String)session.getId();  
  String client_sid = 
    request.getParameter("mysid")==null?"":(String)request.getParameter("mysid");
  java.util.Calendar calendar = java.util.Calendar.getInstance();
  File lf = new File("/usr/tmp/hb.log");    
  try {
    lf.println( "servre sid = "+server_sid);
    lf.println( "client sid = "+client_sid);
    lf.println( "~~~~~");
    lf.close();
  } catch(Exception e)  {
    out.print(e);
  }
  if(!server_sid.equals(client_sid))
    out.print("timeout");
1

There are 1 answers

0
Mark W On

I solved this keep session alive issue with a timed background jquery ajax call to a blank page - The server receives a request every x seconds in the background then. Jquery may be simpler?