The HttpSession Interface in Servlet
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 ‘HttpSessionInterface’. The following diagram explains how Http Sessions work in servlets:

Methods in HttpServlet 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 HttpSession interface 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><head><body><formaction="servlet1">Name:<inputtype="text"name="userName"/><br/><inputtype="submit"value="submit"/></form></body></html>chevron_rightfilter_none -
First.java
// The first servletimportjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;< divclass="noIdeBtnDiv">publicclassFirstextendsHttpServlet {publicvoiddoGet(HttpServletRequest request, HttpServletResponse response){try{/*Declaration of the get method*/response.setContentType("text/html");// Setting the content type to textPrintWriter out = response.getWriter();String n = request.getParameter("userName");/*Fetching the contents ofthe userName field from the form*/out.print("Welcome "+ n);// Printing the usernameHttpSession session = request.getSession();/* Creating a new session*/session.setAttribute("uname", n);/*Setting a variable unamecontaining the value as the fetchedusername as an attribute of the sessionwhich will be shared among different servletsof the application*/out.print("<a href='servlet2'>visit</a>");// Link to the second servletout.close();}catch(Exception e) {System.out.println(e);}}}chevron_rightfilter_none -
Second.java
// The second servletimportjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassSecondServletextendsHttpServlet {publicvoiddoGet(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 createdin the previous servlet usingthe same method that was usedto create the session.The boolean parameter 'false'has been passed so that a new sessionis not created since the session alreadyexists*/String n = (String)session.getAttribute("uname");out.print("Hello "+ n);out.close();}catch(Exception e) {System.out.println(e);}}}chevron_rightfilter_none -
web.xml
<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>chevron_rightfilter_none
Output:
-
index.html :

-
Servlet1 :

-
Servlet2 :

Recommended Posts:
- Difference between Servlet and JSP
- Life Cycle of a Servlet
- Starting with first Servlet Application
- URL Rewriting using Java Servlet
- Servlet Collaboration In Java Using RequestDispatcher and HttpServletResponse
- Hidden Form Field using Annotation | Java Servlet
- Java Servlet and JDBC Example | Insert data in MySQL
- Javax.servlet.http.Cookie class in Java
- Map Interface in Java
- Deque interface in Java with Example
- Java Interface methods
- Nested Interface in Java
- Queue Interface In Java
- BinaryOperator Interface in Java
- NavigableMap Interface in Java with Example
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



