Skip to content
Related Articles

Related Articles

Servlet – Session Tracking

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 14 Mar, 2022

Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver

HTTP is a “stateless” protocol, which means that each time a client requests a Web page, the client establishes a new connection with the Web server, and the server does not retain track of prior requests.

  • The conversion of a user over a period of time is referred to as a session. In general, it refers to a certain period of time.
  • The recording of the object in session is known as tracking.
  • Session tracking is the process of remembering and documenting customer conversions over time. Session management is another name for it.
  • The term “stateful web application” refers to a web application that is capable of remembering and recording client conversions over time.

Why is Session Tracking Required?

  • Because the HTTP protocol is stateless, we require Session Tracking to make the client-server relationship stateful.
  • Session tracking is important for tracking conversions in online shopping, mailing applications, and E-Commerce applications.
  • The HTTP protocol is stateless, which implies that each request is treated as a new one. As you can see in the image below.

Deleting Session Data

We have numerous alternatives once you’ve finished processing a user’s session data.

  1. Remove a specific attribute You can delete the value associated with a specific key by calling the public void removeAttribute(String name) function.
  2. Delete your whole session. To delete an entire session, use the public void invalidate() function.
  3. Setting Session Timeout You may set the timeout for a session separately by calling the public void setMaxInactiveInterval(int interval) function.
  4. Log the user out On servers that support servlets 2.4, you may use the logout method to log the client out of the Web server and invalidate all of the users’ sessions.
  5. web.xml Configuration If you’re using Tomcat, you may set the session timeout in the web.xml file, in addition to the ways listed above.
<session-config>
  <session-timeout>20</session-timeout>
</session-config>

The timeout is specified in minutes and overrides Tomcat’s default timeout of 30 minutes.

In a servlet, the getMaxInactiveInterval() function delivers the session’s timeout period in seconds. GetMaxInactiveInterval() returns 900 if your session is set to 20 minutes in web.xml.

Session Tracking employs Four Different techniques

  1. Cookies
  2. Hidden Form Field
  3. URL Rewriting
  4. HttpSession

A. Cookies

Cookies are little pieces of data delivered by the web server in the response header and kept by the browser. Each web client can be assigned a unique session ID by a web server. Cookies are used to keep the session going. Cookies can be turned off by the client.

B. Hidden Form Field

The information is inserted into the web pages via the hidden form field, which is then transferred to the server. These fields are hidden from the user’s view.

Illustration:

<input type = hidden'  name = 'session' value = '12345' >

C. URL Rewriting

With each request and return, append some more data via URL as request parameters. URL rewriting is a better technique to keep session management and browser operations in sync.

D. HttpSession

A user session is represented by the HttpSession object. A session is established between an HTTP client and an HTTP server using the HttpSession interface. A user session is a collection of data about a user that spans many HTTP requests.

Illustration:

HttpSession session = request.getSession( );
Session.setAttribute("username", "password");

The request must be made. Before sending any document content to the client, you must first call getSession(). The following is a list of the most significant methods provided by the HttpSession object:

Method

Description

public Object getAttribute(String name) This method returns the object in this session bound with the supplied name, or null if no object is bound with the name.
public Enumeration getAttributeNames() This function returns an Enumeration of String objects with the names of all the items associated with this session.
public long getCreationTime() This method returns the milliseconds since midnight January 1, 1970 GMT, when this session was created.
public String getId() This function returns a string that contains the session’s unique identification.
public long getLastAccessedTime() This function returns the session’s most recent accessible time in milliseconds since midnight on January 1, 1970 GMT.
public int getMaxInactiveInterval() The maximum time interval (seconds) for which the servlet container will keep the session open between client requests is returned by this function.
public void invalidate() This function unbinds any objects connected to this session and invalidates it.
public boolean isNew() If the client is unaware of the session or decides not to join it, this function returns true.
public void removeAttribute(String name) The object bound with the supplied name is removed from this session using this method.
public void setAttribute(String name, Object value) This function uses the supplied name to tie an object to this session.
public void setMaxInactiveInterval(int interval) This function defines the interval between client requests before the servlet container invalidates this session in seconds.

Implementation: It depicts how to get the creation and last-accessed times for a session using the HttpSession object. If the request does not already have a session associated with it, we will create one.

A. File: GfgSession.java

Java




// Java Program to Illustrate Creation and last-accessed
// Times for a Session
 
// Import required java libraries
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
// Extend HttpServlet class
public class GfgSession extends HttpServlet {
 
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException
    {
 
        // Create a session object if it is already not
        // created.
        HttpSession session = request.getSession(true);
 
        // Get session creation time.
        Date createTime
            = new Date(session.getCreationTime());
 
        // Get last access time of this web page.
        Date lastAccessTime
            = new Date(session.getLastAccessedTime());
 
        String title = "Welcome Back to geeksforgeeks";
        Integer visitCount = new Integer(0);
        String visitCountKey = new String("visitCount");
        String userIDKey = new String("userID");
        String userID = new String("GFG");
 
        // Check if this is new comer on your web page.
        if (session.isNew()) {
            title = "Welcome to GeeksForGeeks";
            session.setAttribute(userIDKey, userID);
        }
        else {
            visitCount = (Integer)session.getAttribute(
                visitCountKey);
            visitCount = visitCount + 1;
            userID
                = (String)session.getAttribute(userIDKey);
        }
        session.setAttribute(visitCountKey, visitCount);
 
        // Set response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
 
        String docType
            = "<!doctype html public \"-//w3c//dtd html 4.0 "
              + "transitional//en\">\n";
 
        out.println(
            docType + "<html>\n"
            + "<head><title>" + title + "</title></head>\n"
            +
 
            "<body bgcolor = \"#f0f0f0\">\n"
            + "<h1 align = \"center\">" + title + "</h1>\n"
            + "<h2 align = \"center\">Gfg Session Information</h2>\n"
            + "<table border = \"1\" align = \"center\">\n"
            +
 
            "<tr bgcolor = \"#949494\">\n"
            + "  <th>Session info</th><th>value</th>"
            + "</tr>\n"
            +
 
            "<tr>\n"
            + "  <td>id</td>\n"
            + "  <td>" + session.getId() + "</td>"
            + "</tr>\n"
            +
 
            "<tr>\n"
            + "  <td>Creation Time</td>\n"
            + "  <td>" + createTime + "  </td>"
            + "</tr>\n"
            +
 
            "<tr>\n"
            + "  <td>Time of Last Access</td>\n"
            + "  <td>" + lastAccessTime + "</td>"
            + "</tr>\n"
            +
 
            "<tr>\n"
            + "  <td>User ID</td>\n"
            + "  <td>" + userID + "</td>"
            + "</tr>\n"
            +
 
            "<tr>\n"
            + "  <td>Number of visits</td>\n"
            + "  <td>" + visitCount + "</td>"
            + "</tr>\n"
            + "</table>\n"
            + "</body>"
            + "</html>");
    }
}


 

 

B. File: web.xml

 

XML




<web-app>
<servlet>
   <servlet-name>GfgSession</servlet-name>
   <servlet-class>GfgSession</servlet-class>
</servlet>
 
<servlet-mapping>
   <servlet-name>GfgSession</servlet-name>
   <url-pattern>/GfgSession</url-pattern>
</servlet-mapping>
</web-app>


Compile the servlet SessionTrack described above and add it to the web.xml file. When you run http://localhost:8080/SessionTrackingGfg/GfgSession for the first time, you should get the following result:

Output:

If we try to run the same servlet again, we will get the following result.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!