Servlet HttpSession Management
Session tracking is a mechanism that is used to maintain state about a series of requests from the same user. Java Servlet technology provides an API for managing sessions and allows several mechanisms for tracking sessions. One of the best approach is by using HttpSession object. HttpSession interface is defined in "javax.servlet.http" package and is used for the purpose of session tracking while working with servlets.
we can access a session by calling the HttpServletRequest.getSession() or HttpServletRequest.getSession(boolean) method of a request object. This method will return the current session associated with this request or if the request does not have any session, it will create a new one.
A sample Program demonstrating the usage of HttpSession
import java.io.*;Read more...
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
class HttpSessionEx extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println( "<HTML><BODY>" );
HttpSession sess = request.getSession(true);
// HttpSession Methods
Date cd = new Date(sess.getCreationTime());
Date acd = new Date(sess.getLastAccessedTime());
out.println("Session ID " + sess.getId());
out.println("Session was Created at: " + cd);
out.println("Session was Last Accessed at: " + acd);
// getting the session item
Object sessobj = sess.getAttribute( "power" );
out.println( "<BR>" + sessobj );
// getting the contents of the session
Enumeration data = sess.getAttributeNames();
while( data.hasMoreElements() ) {
String value = (String) data.nextElement();
sessobj = sess.getAttribute(value);
out.println( "<BR>" + value + " = " + sessobj );
}
out.println( "</BODY></HTML>" );
}
}