java4all@1986 java. Powered by Blogger.

How to know the session last acess time?

>> Tuesday, June 7, 2011

This example illustrates to find current  access time of session  and last access time of session.
Sessions are used to maintain state and user identity across multiple page requests.
An implementation of HttpSession represents the server's view of the session.
The server considers a session to be new until it has been joined by the client.
Until the client joins the session, isNew() method returns true.

LastAcessTime Class


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LastAccessTime extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String head;
Integer count = new Integer(0);
if (session.isNew()) {
head = "New Session Value ";
} else {
head = "Old Session value";
Integer oldcount =(Integer)session.getValue("count");
if (oldcount != null) {
count = new Integer(oldcount.intValue() + 1);
}
}
session.putValue("count", count);
out.println("<HTML><BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H2 ALIGN=\"CENTER\">" + head + "</H2>\n" +
"<H4 ALIGN=\"CENTER\">Session Access Time:</H4>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"pink\">\n" +
"<TD>Session Creation Time\n" +" <TD>" +
new Date(session.getCreationTime()) + "\n" +
"<TR BGCOLOR=\"pink\">\n" +" <TD>Last Session Access Time\n" +
" <TD>" + new Date(session.getLastAccessedTime()) +
"</TABLE>\n" +"</BODY></HTML>");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Description of code: In  the above servlet,  isNew() method is used to find whether session is new or old.
The getCreationTime() method is used to find  the time when session was created.
The getLastAccessedTime() method is used to find when last time session was accessed by the user.

web.xml

  LastAccessTime
  LastAccessTime
 

  LastAccessTime
  /LastAccessTime

0 comments:

Post a Comment

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP