Servlet HttpSession

HttpSession:

HttpSession is an interface that provides a way to identify a user in multiple page requests. A unique session ID is given to the user when the first request comes. This ID is stored in a request parameter or in a cookie.

How to get a session object?

HttpServletRequest interface’s getSession() method is used to get the session object.

Syntax:

HttpSession session = request.getSession();

How to set attributes in the session objects?

HttpSession interface’s setAttribute() method is used to set attributes in the session object.

Syntax:

public void setAttribute(String name,Object value);

Example:

session.setAttribute("attName", "attValue");

How to get an attribute from the session object?

HttpSession interface’s getAttribute() method is used to get attributes from the session object.

Syntax:

public Object getAttribute(String name);

Example:

String value = (String) session.getAttribute("attName");

Session management example using HttpSession:

LoginServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* This class is used to set values in session.
* @author W3schools360
*/
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
   //no-argument constructor
    public LoginServlet() {
       
    }

    protected void doPost(HttpServletRequest request, 
           HttpServletResponse response)
                   throws ServletException, IOException {
    response.setContentType("text/html"); 
        PrintWriter out = response.getWriter();
        
        //get parameters from request object.
        String userName = request.getParameter("userName").trim();
        String password = request.getParameter("password").trim();
        
        //check for null and empty values.
        if(userName == null || userName.equals("") || 
                password == null || password.equals("")){
            out.print("Please enter both username " +
                    "and password. <br><br>");
            RequestDispatcher requestDispatcher = 
                request.getRequestDispatcher("/login.html");
            requestDispatcher.include(request, response);
        }//Check for valid username and password.
        else if(userName.equals("jai") && password.equals("1234")){
            HttpSession session=request.getSession();  
                session.setAttribute("userName",userName);  
                session.setAttribute("password",password);
            out.println("Logged in successfully.<br>"); 
            out.println("Click on the below link to see " +
                "the values of Username and Password.<br>");
            out.println("<a href="DisplaySessionValueServlet">" +
                    "Click here</a>");
            out.close();
        }else{
            out.print("Wrong username or password. <br><br>");
            RequestDispatcher requestDispatcher = 
                request.getRequestDispatcher("/login.html");
            requestDispatcher.include(request, response);
        }
    }
}

 

DisplaySessionValueServlet.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;

/**
* This class is used to get values from session.
* @author W3schools360
*/
public class DisplaySessionValueServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    //no-argument constructor
    public DisplaySessionValueServlet() {
       
    }

    protected void doGet(HttpServletRequest request, 
	    HttpServletResponse response)
	             throws ServletException, IOException {
	response.setContentType("text/html"); 
    	PrintWriter out = response.getWriter();
    	
    	//get parameters from session object.
    	HttpSession session=request.getSession(false);  
        String userName =(String)session.getAttribute("userName");  
        String password =(String)session.getAttribute("password");  
    	
    	out.println("Username: " + userName + "");
    	out.println("Password: " + password);
    	
    	out.close();
    }
}

login.html

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>


    <form action="LoginServlet" method="post">
        Username:<input type="text" name="userName">
        <br><br>
        Password:<input type="password" name="password">
        <br><br> 
        <input type="submit" value="login"> 
    </form>

web.xml

<!--?xml version="1.0" encoding="UTF-8"?-->
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>
        com.w3schools.business.LoginServlet
    </servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  
  <servlet>
    <servlet-name>DisplaySessionValueServlet</servlet-name>
    <servlet-class>
        com.w3schools.business.DisplaySessionValueServlet
    </servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>DisplaySessionValueServlet</servlet-name>
    <url-pattern>/DisplaySessionValueServlet</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>login.html</welcome-file>
  </welcome-file-list>
  
</web-app>