The HttpSession Interface in Servlet
Last Updated :
25 Apr, 2022
What is a session?
In web terminology, a session is simply the limited interval of time in which two systems communicate with each other. The two systems can share a client-server or a peer-to-peer relationship. However, in Http protocol, the state of the communication is not maintained. Hence, the web applications that work on http protocol use several different technologies that comprise
Session Tracking, which means maintaining the state (data) of the user, in order to recognize him/her.
In order to achieve session tracking in servlets, cookies have been one of the most commonly used tech. However, they have the following disadvantages:
- They can only keep textual information.
- They're browser dependent. Hence, if the client disables them, your web application can't make use of them
- Individual cookie can contain not more than 4kb of information
How to create sessions with a unique session id for each user in java servlet
For this, servlets provide an interface called
'HttpSession' Interface. The following diagram explains how Http Sessions work in servlets:
Methods in HttpSession Interface
Method |
Description |
public HttpSession getSession() |
Gets the HttpSession object. If the request doesn't have a session associated with it, a new session is created |
public HttpSession getSession(boolean create) |
Gets the session associated with the request. If not already present, then a new one is created based on the value of the boolean argument passed into it |
public String getId() |
Returns the unique session id |
public long getCreationTime() |
It returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. |
public long getLastAccessedTime() |
It returns the time when this session was last accessed, measured in milliseconds since midnight January 1, 1970 GMT. |
public long getLastAccessedTime() |
It returns the time when this session was last accessed, measured in milliseconds since midnight January 1, 1970 GMT. |
public void invalidate() |
Invalidates the session |
Advantages of Http Sessions in Servlet
- Any kind of object can be stored into a session, be it a text, database, dataset etc.
- Usage of sessions is not dependent on the client's browser.
- Sessions are secure and transparent
Disadvantages of Http session
- Performance overhead due to session object being stored on server
- Overhead due to serialization and de-serialization of data
Example of Session tracking using HttpServlet Interface: In the below example the setAttribute() and getAttribute() methods of the HttpServlet class is used to create an attribute in the session scope of one servlet and fetch that attribute from the session scope of another servlet.
-
index.html
html
<html>
<head>
<body>
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
-
First.java
Java
// The first servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
< div class
= "noIdeBtnDiv" > public class First extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try { /*Declaration of the get method*/
response.setContentType("text/html"); // Setting the content type to text
PrintWriter out = response.getWriter();
String n = request.getParameter("userName"); /*Fetching the contents of
the userName field from the form*/
out.print("Welcome " + n); // Printing the username
HttpSession session = request.getSession(); /* Creating a new session*/
session.setAttribute("uname", n);
/*Setting a variable uname
containing the value as the fetched
username as an attribute of the session
which will be shared among different servlets
of the application*/
out.print("<a href='servlet2'>visit</a>"); // Link to the second servlet
out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
-
Second.java
Java
// The second servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) try {
/*Declaration of the get method*/
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(false);
/*Resuming the session created
in the previous servlet using
the same method that was used
to create the session.
The boolean parameter 'false'
has been passed so that a new session
is not created since the session already
exists*/
String n = (String)session.getAttribute("uname");
out.print("Hello " + n);
out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
-
web.xml
html
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Second</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Output:
index.html :

Servlet1 :

Servlet2 :

Similar Reads
Servlet - HttpSessionEvent and HttpSessionListener In Java, HttpSessionEvent is a class, which is representing event notifications for changes or updates to sessions within a web application. Similarly, the interface for this event is HttpSessionListener, which is for receiving notification events about HttpSession lifecycle changes. As a means to,
3 min read
Servlet - HttpSession Login and Logout Example In general, the term "Session" in computing language, refers to a period of time in which a user's activity happens on a website. Whenever you login to an application or a website, the server should validate/identify the user and track the user interactions across the application. To achieve this, J
8 min read
Servlet - Single Thread Model Interface Single Thread Model Interface was designed to guarantee that only one thread is executed at a time in a given servlet instance service method. It should be implemented to ensure that the servlet can handle only one request at a time. It is a marker interface and has no methods. Once the interface is
3 min read
Servlet - Authentication Filter 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. Authentication Filter In Servlets Authentication may
2 min read
Java Servlet Filter with Example A filter is an object that is invoked at the preprocessing and postprocessing of a request on the server, i.e., before and after the execution of a servlet for filtering the request. Filter API (or interface) includes some methods which help us in filtering requests. To understand the concept of Fil
4 min read