Back to: Java Servlets Tutorials
HttpSession Session Tracking Mechanism in Servlet
In this article, I am going to discuss the HttpSession Session Tracking Mechanism in Java Servlet. Please read our previous article where we discussed URL-Rewriting Session Tracking Mechanism. At the end of this article, you will understand the following pointers in detail.
- HttpSession Interface
- Creating an HttpSession object in Servlet
- Understanding getSession() and getSession(false) methods
- HttpSession Methods
- Advantages and Disadvantages of HttpSession Session Tracking Mechanism
- Understanding HttpSession with an Example in Java Servlet
- Login and Logout Example using HttpSession in Servlet
HttpSession Interface:
In HttpSession Session Tracking Mechanism, we will create a separate HttpSession object for each and every user at each and every request we will pick up the request parameters from the request object and we will store them in the respective HttpSession object for the sale of future reusability.
After keeping the request parameters data in the HttpSession object we have to generate the next form at the client browser by forwarding the request to the particular static page or by generating a dynamic form.
Creating HttpSession object in Java Servlet
In HttpSession Session Tracking Mechanism, to create HttpSession object we will use either of the following methods:
- req.getSession();
- req.getSession(false);
Both the methods can be used to return HttpSession object.
getSession() method
To get HttpSession object if we getSession() method then container will check whether any HttpSession object existed for the respective user or not, if any HttpSession object is existed then container will return the existed HttpSession object reference. If no object is existed for the respective user then container will create a new HttpSession object and return its reference.
public HttpSession getSession()
Example: HttpSession hs=req.getSession();
getSession(false) method
To get HttpSession object if we getSession(false) method then container will check whether any HttpSession object existed w.r.t. user or not, if any HttpSession object is existed then container will return that HttpSession object reference. If no HttpSession object is existed then container will return null value without creating new HttpSession object.
public HttpSession getSession(boolean b)
Example: HttpSession hs=req.getSession(false);
Note: getSession(true) method functionality is almost all same as getSession() method.
HttpSession Methods
- public void invalidate(): To destroy the HttpSession object we will use this method.
- public void setMaxInactiveInterval(int time): If we want to destroy the HttpSession object after a particularly ideal time duration then we have to use this method.
- public void setAttribute(String name, Object value): To set an attribute on to the HttpSession object we have to use this method.
- public Object getAttribute(String name): To get a particular attribute value from the HttpSession object we have to use this method.
- public Enumeration getAttributeNames(): To get all attribute names from the HttpSession object we have to use the following method.
- public void removeAttribute(String name): To remove an attribute from the HttpSession object we have to use the following method.
Advantages of HttpSession Session Tracking
- There are no restrictions on the size of the object, any kind of object can be stored in a session.
- The usage of the session is not dependent on the client’s browser.
- It is secure and transparent.
Disadvantages of HttpSession Session Tracking
- We will create a HttpSession object for each and every user, where if we increase the number of users then automatically the number of HttpSession objects will be created at the server machine, it will reduce the overall performance of the web application.
- We are able to identify user-specific HttpSession objects among multiple numbers of HttpSession objects by carrying Session-Id value from client to server and from server to client.
- In the above context, if the client browser disables Cookies then HttpSession Session Tracking Mechanism will not execute its functionality.
HttpSession Example in Java Servlet
In this example, we are setting the attribute in the session scope in one servlet (SessionId1.java) and getting that value from the session scope in another servlet (SessionId2.java). To set the attribute in the session scope, we have used the setAttribute() method of the HttpSession interface and to get the attribute, we have used the getAttribute method.
index.html
<html> <form action="./welcome"> Enter name:<input type="text" name="username"> Enter Email:<input type="text" name="emailId"> <input type="submit" value="submit"> </form> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0"> <servlet> <servlet-name> SessionId1 </servlet-name> <servlet-class> SessionId1 </servlet-class> </servlet> <servlet> <servlet-name> SessionId2 </servlet-name> <servlet-class> SessionId2 </servlet-class> </servlet> <servlet-mapping> <servlet-name> SessionId1 </servlet-name> <url-pattern> /welcome </url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name> SessionId2 </servlet-name> <url-pattern> /servlet2 </url-pattern> </servlet-mapping> </web-app>
SessionId1.java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class SessionId1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); //get the value from the text from HTML String uname = request.getParameter("username"); String email = request.getParameter("emailId"); //Create HttpSession object HttpSession session = request.getSession(); //set the username in the session session.setAttribute("uname", uname); session.setAttribute("emailId", email); out.print("<h2>Enter your country:<input type='text' name='country'></h2>"); out.println("<a href='servlet2'><h2>go</h2></a>"); out.flush(); out.close(); } }
SessionId2.java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class SessionId2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); //get the values from the request String country = request.getParameter("country"); HttpSession session = request.getSession(false); //This from get sessionID String sessionId = session.getId(); //Get the username from the session String userName = (String)session.getAttribute("uname"); //Get the emailId from the session String email = (String)session.getAttribute("emailId"); out.println("<h2>This is your name get from the session::"+userName+"</h2>"); out.println("<h2>This is your emailId get from the session::"+email+"</h2>"); out.println("<h2>This is your country it shows null because it is not in session ::"+country+"</h2>"); out.println("<h2>This is the sessionId value :::"+sessionId+"</h2>"); out.flush(); out.close(); } }
Output
Login and Logout Example using HttpSession in Servlet
In this example, we have an index.html page where a login form is displayed. When the user enters login details (Email Id and Password) and submits the form the request is sent to LoginServlet. If the details are correct then the user will be redirected to HomeServlet otherwise redirected to index.html. LogoutServlet invalidates the sessions to logout the user and redirected to index.html. If anyone tries to access the Home page directly without doing login then the user will be redirected to index.html.
index.html
<html> <head> <title>Login and Logout With Session Example</title> </head> <body> <form action="login" method="post"> Email: <input type="email" name="email" required/><br/><br/> Password: <input type="password" name="pass" required/><br/><br/> <input type="submit" value="Login"/> </form> </body> </html>
LoginServlet.java
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/login") public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("email"); String pass = request.getParameter("pass"); if(email.equals("java@gmail.com") && pass.equals("java")) { HttpSession session = request.getSession(); session.setAttribute("email", email); response.sendRedirect("home"); } else { response.sendRedirect("index.html"); } } }
HomeServlet.java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/home") public class HomeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pr = response.getWriter(); HttpSession session = request.getSession(false); if(session != null) { String email = (String) session.getAttribute("email"); pr.print("Welcome " + email); pr.print("<br/><a href=\"logout\">Logout</a>"); } else { response.sendRedirect("index.html"); } pr.close(); } }
LogoutServlet.java
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/logout") public class LogoutServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.invalidate(); response.sendRedirect("index.html"); } }
Output
In the next article, I am going to discuss Event and Listener in Servlet. Here, in this article, I try to explain the HttpSession Session Tracking Mechanism in Java Servlet with Examples. I hope you enjoy this HttpSession Session Tracking Mechanism in Java Servlet article.