☰ See All Chapters |
HttpSession in Servlet
Unlike Session Management with Cookies, client can send many requests to the application and the application has to remember all the requests coming from the client. Registration applications have to remember data from different pages like personal profile, education details, professional details etc.… Before client presses confirm/register button. There will also be multiple clients accessing the same application with multiple requests. When we use HttpSession object (when we create HttpSession object) to store client specific data, automatically one value called JSESSIONID generated by the server for every client, is exchanged between the client and server to keep track of session. By default JSESSIONID is exchanged between the client and server using cookies. Once HttpSession object is created, JSESSIONID is generated by the server and is added to cookie object; since cookie is exchanged between client and server automatically we need not to keep track of session.
HttpSession interface
The HttpSession interface enables a servlet to read and write the state information that is associated with an HTTP session. Several of its methods are summarized in below table; these methods throw an IllegalStateException if the session has already been invalidated.
Method | Description |
void setAttribute(String attr, Object val) | Associates the value passed in val with the attribute name passed in attr. |
Object getAttribute(String attr) | Returns the value associated with the name passed in attr. Returns null if attr is not found |
Enumeration getAttributeNames( ) | Returns an enumeration of the attribute names associated with the session. |
void removeAttribute(String attr) | Removes the attribute specified by attr from the session. |
void invalidate( ) | Invalidates this session and removes it from the context. |
String getId( ) | Returns the session ID. |
long getLastAccessedTime( ) | Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when the client last made a request for this session. |
boolean isNew( ) | Returns true if the server created the session and it has not yet been accessed by the client. |
long getCreationTime( ) | Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when this session was created. |
How to get the HttpSession object
The HttpServletRequest interface provides two methods to get the object of HttpSession:
public HttpSession getSession()
public HttpSession getSession(boolean create)
getSession() getSession(true) | getSession(false) |
Returns already created session object. If the session object is not yet created then returns new session object. | Is session object is already created then it will be returned otherwise returns null. |
Example of HttpSession
Project directory structure
home.html
<!DOCTYPE html> <html> <body> <form action="../servlet1" method="post"> Enter Personal Details:<br /> Name:<input type="text" name="name" /><br /> <input type="submit" value="go" /> </form> </body> </html> |
FirstServlet.java
package com.java4coding;
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class FirstServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); out.print("Welcome " + name); HttpSession httpSession = request.getSession(); httpSession.setAttribute("name", name); out.print("<form action='servlet2' method='post'> "); out.print("Enter Contact Details:<br/>"); out.print("Address:<input type='text' name='address'/><br/>"); out.print("<input type='submit' value='go'/> "); out.print("</form>"); out.close(); } catch (Exception e) { System.out.println(e); } } } |
SecondServlet.java
package com.java4coding;
import java.io.*; import javax.servlet.http.*;
public class SecondServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String address = request.getParameter("address"); HttpSession httpSession = request.getSession(); httpSession.setAttribute("address", address); out.print("<form action='servlet3' method='post'> "); out.print("Enter Eduction Details:<br/>"); out.print("Education:<input type='text' name='education'/><br/>"); out.print("<input type='submit' value='go'/> "); out.print("</form>"); out.close(); } catch (Exception e) { System.out.println(e); } } } |
ThirdServlet.java
package com.java4coding;
import java.io.*;
import javax.servlet.*; import javax.servlet.http.*;
public class ThirdServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession httpSession = request.getSession(); Cookie ck[] = request.getCookies(); out.print("Name: " + httpSession.getAttribute("name") + "</br>"); out.print("Address: " + httpSession.getAttribute("address") + "</br>"); out.print("Education: " + request.getParameter("education")); out.close(); } catch (Exception e) { System.out.println(e); } } } |
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:web="https://xmlns.jcp.org/xml/ns/javaee"> <servlet> <servlet-name>s1</servlet-name> <servlet-class>com.java4coding.FirstServlet</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>com.java4coding.SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> <servlet> <servlet-name>s3</servlet-name> <servlet-class>com.java4coding.ThirdServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s3</servlet-name> <url-pattern>/servlet3</url-pattern> </servlet-mapping> </web-app> |
Output
All Chapters