Session Tracking in Servlets

HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism.

A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession object is returned. This object can store a set of bindings that associate names with
objects. The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these bindings.


import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession hs = request.getSession(true);
PrintWriter pw = response.getWriter();
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);