Thursday, 29 May 2014

Servlets : HttpSession Attribute

Master Java & Servlet Development!

Subscribe to Ram N Java for beginner-friendly coding walkthroughs, session handling deep dives, and core web architecture guides!

🔔 Subscribe to Ram N Java

What is Session Scope in Java Servlets?

In Java web applications, HTTP is a stateless protocol, meaning each client request is independent and the server does not retain identity information across requests by default. To preserve user data—such as login states or shopping cart contents—across multiple HTTP requests from the same user, the servlet container provides the HttpSession interface.

The Session Scope allows you to store objects as key-value pairs (attributes) associated with a specific user's session. As long as the session remains active and has not timed out or been invalidated, any servlet or JSP in the same web application can access those attributes for that specific user.

Setting and Getting Attributes in HttpSession

Working with session attributes involves three primary steps using standard methods available in HttpSession:

  • Obtain the Session: Use HttpSession session = request.getSession(); to fetch the active session or create a new one if it doesn't already exist.
  • Store an Attribute: Use session.setAttribute(String name, Object value); to bind an object to the user's session.
  • Retrieve an Attribute: Use session.getAttribute(String name); to look up the stored object, casting it back to its specific type.
  • Remove an Attribute: Use session.removeAttribute(String name); when the stored data is no longer needed.
// Step 1: Access the current session
HttpSession session = request.getSession();

// Step 2: Store user data in session scope
session.setAttribute("currentUser", "JohnDoe");

// Step 3: Retrieve user data across different servlets
String user = (String) session.getAttribute("currentUser");

Key Rules to Remember

  • User-Specific Data: Unlike application-wide ServletContext attributes, session attributes belong exclusively to a single user.
  • Persistence Across Requests: Attributes remain accessible across multiple browser requests until the session times out, the browser closes (session cookie expires), or session.invalidate() is called.
  • Object Type Flexibility: You can bind any Java object (Strings, Collections, custom JavaBean models) to the session scope.

Recommended Related Tutorials

Continue mastering session management and attributes with these tutorials from Ram N Java:


Click here to watch in Youtube : https://www.youtube.com/watch?v=NXMCnNxBip0

Click the below Image to Enlarge

HttpSessionAttributeDemo Project Dir Structure   

FirstServlet.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 FirstServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException
    {
        System.out.println("----------------------------------------------");
        System.out.println(" Init method is called in "
                + this.getClass().getName());
        System.out.println("--------------------------------------------");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        out.print("Welcome " + username);

        HttpSession session = request.getSession();
        System.out.println("FirstServlet sessionid :" + session.getId());
        session.setAttribute("Username", username);
        session.setAttribute("Role", "Admin");

        out.print("<a href='servlet2'> : visit</a>");

        out.close();

    }

    public void destroy()
    {
        System.out.println("----------------------------------------------");
        System.out.println(" destroy method is called in "
                + this.getClass().getName());
        System.out.println("----------------------------------------------");
    }

}

SecondServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

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 SecondServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException
    {
        System.out.println("----------------------------------------------");
        System.out.println(" Init method is called in "
                + this.getClass().getName());
        System.out.println("----------------------------------------------");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession();

        System.out.println("Second Servlet sessionid :" + session.getId());

        String userName = (String) session.getAttribute("Username");
        out.print("Hello " + userName + "<br>");

        out.print("*************************************************************"
                + "<br>");

        Enumeration<String> namesEnum = session.getAttributeNames();
        while (namesEnum.hasMoreElements())
        {
            String name = (String) namesEnum.nextElement();
            String value = (String) session.getAttribute(name);
            out.print(name + ":" + value);
            out.print("<br>");

        }

        out.close();
    }

    public void destroy()
    {
        System.out.println("----------------------------------------------");
        System.out.println(" destroy method is called in "
                + this.getClass().getName());
        System.out.println("----------------------------------------------");
    }

}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    metadata-complete="true" version="3.0">

    <display-name>HttpSessionAttributeDemo</display-name>

    <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>

    <servlet>
        <servlet-name>s1</servlet-name>
        <servlet-class>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>SecondServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>s2</servlet-name>
        <url-pattern>/servlet2</url-pattern>
    </servlet-mapping>

</web-app>

index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Multiple Filters Demo</title>
</head>
<body>
    <form action="servlet1" method="GET">
        
        UserName :  <input type="text" name="username" /><br /> 
        
        Password :&nbsp; &nbsp; <input type="password" name="password" /><br /> 
            
        <input type="submit" value="login" />
        
    </form>
</body>
</html>


Environment Used 

JDK version :1.7.0_51
Tomcat version : 7.0.50 

To Download HttpSessionAttributeDemoApp Project Click the below link

https://sites.google.com/site/javaee4321/servlets/HttpSessionAttributeDemoApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • No comments:

    Post a Comment

    Tutorials