Session Tracking in Servlet

As of now, we have discussed Cookies in Servlet. As we know, HTTP  which is a stateless protocol means for each client request there is a separate connection to the web server.we have seen ways to maintain a session between client and web. In this article, we will see Session Tracking, its method, and an example showing Session Tracking.

Session in servlet

Servlet provides the HttpSession Interface which provides a way to identify a user across more than one page. Session means a particular interval of time. Session Tracking is used to keep the state of the user across pages. The following are the methods we used for session tracking.

Cookies in servlet

One way we have seen earlier is Cookies. A webserver assign uniques session Id to each request. But the cookie is not recommended by many because many browsers don’t support cookies.

Hidden Form Fields

Another way is Hidden Form Fields In this a webserver can send hidden HTML form filed with session Id. But this is not a good way because <a href > tag does not result in form submission.so this method does not support session Tracking.

<input type = "hidden" name = "session_id" value = "abc">

URL Rewriting

One more way is URL Rewriting. In this extra data is appended at the end of the URL that identifies the session. It is a better method as compared to both Cookies and Hidden form fields. The drawback here is we have to generate a URL dynamically to assign a session ID.

http://codedec.com/first.html;sessionid=abc

Http session Object

Servlet provides us an interface of Httpsession for session tracking. In this, the Servlet container creates a separate session-id for the users which helps in identifying a user in the system. (like we have unique Roll no in school).We get the object  by calling method getSession() of HttpServletRequest.

HttpSession session=request.getSession()

Methods of HttpSession Interface

  • public String getId(): This method returns the id value.
  • public long getCreationtime(): This method returns the time at which the session is created.
  • public long getLastAccessedTime(): This method returns the last time at which the user sends a request associated with the session id.
  • public void invalidate(): This method invalidates the object.
  • public Object getAttribute(String name): This method returns the object bound to the specified name in the session.
  • public Enumeration getAttributeNames(): This method returns all the objects associated with the session.
  • public int getMaxInactiveInterval(): This method returns the maximum time that the servlet will keep the session between client and server.
  • public boolean isNew(): This method returns true if the client does not know about the session.
  • public void removeAttribute(String name): This method returns the object bound to the specified name.
  • public void setAttribute(): This method sets the object to the session.
  • public void setMaxInactiveInterval(int interval): This method sets the time in which between the client request before the web container invalidates the session.

How to track session in servlet

In this example, we simply create a login page and create the HttpSession for the request.

index.html

<form action="FirstServlet" method="get">
Username<input type="text" name="uname">
<br>
Password<input type="password" name="pass"><br>
<input type="submit" value="Login" id="button-1"/>
</form>

FirstServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    response.setContentType("text/html");
    PrintWriter printWriter=response.getWriter();
    String uname=request.getParameter("uname");
    String pass=request.getParameter("pass");
    printWriter.println("<br>Hello "+uname);
    printWriter.println("<br> My password is "+pass);
    HttpSession httpSession=request.getSession();
      httpSession.setAttribute("uname",uname);
      httpSession.setAttribute("pass",pass);
      printWriter.println("<br><a href='SecondServlet'>Go to Profile</a>");
  }

SecondServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html");
    PrintWriter printWriter=response.getWriter();
    HttpSession httpSession=request.getSession();
    String uname=(String) httpSession.getAttribute("uname");
    String pass=(String) httpSession.getAttribute("pass");
    printWriter.println("<br> Username :"+uname+"<br>My Password is :"+pass);
    
  }

Web.xml

<servlet>
    <servlet-name>FirstServlet</servlet-name>
    <servlet-class>FirstServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FirstServlet</servlet-name>
    <url-pattern>/FirstServlet</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>SecondServlet</servlet-name>
    <servlet-class>SecondServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SecondServlet</servlet-name>
    <url-pattern>/SecondServlet</url-pattern>
  </servlet-mapping>