Showing posts with label HttpSession. Show all posts
Showing posts with label HttpSession. Show all posts

Saturday, 11 April 2015

Servlets : What is Session Tracking?

🚀 Master Java & Servlets with Ram N Java!

Subscribe to get clear, beginner-friendly tutorials right when they drop.

🔔 Subscribe to Ram N Java

What is Session Tracking?

The Hypertext Transfer Protocol (HTTP) is a stateless protocol. This means each request sent by a client to a server is executed independently without retaining any knowledge or context from earlier requests.

Session Tracking (also known as session management) is the mechanism used by web applications to maintain state and recognize requests originating from the same client across multiple pages or requests.

Why Do We Need Session Tracking?

Modern web applications require continuity and personalization across user interactions:

  • User Authentication: Remembering a logged-in user so they do not need to enter credentials on every single page navigation.
  • E-Commerce Carts: Retaining items added to a shopping cart across multiple product pages until checkout.
  • Multi-Step Wizards: Preserving progress, user inputs, and form data across multi-page questionnaires or surveys.

Common Techniques for Session Tracking in Servlets

The Java Servlet specification provides four standard techniques to achieve session tracking:

  1. Cookies: Small pieces of key-value data stored on the client browser and sent to the server in subsequent request headers.
  2. Hidden Form Fields: Embedding invisible form elements (<input type="hidden">) inside HTML pages to carry identifiers across requests.
  3. URL Rewriting: Appending session identifiers directly to the URL string (useful when client browsers disable cookies).
  4. HttpSession API: A high-level, container-managed session interface that stores arbitrary session attributes on the server side.

Recommended Next Watch

Deepen your grasp of session management in Java Servlets with these related tutorials:


Click here to watch in Youtube : https://www.youtube.com/watch?v=VLg7WV5L0S4&list=UUhwKlOVR041tngjerWxVccw&index=1

Click the below Image to Enlarge
Servlets : What is Session Tracking?
Servlets : What is Session Tracking?
Servlets : What is Session Tracking?
See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • Servlets : Session Tracking API

    🚀 Master Java & Servlets with Ram N Java!

    Subscribe to get clear, beginner-friendly tutorials right when they drop.

    🔔 Subscribe to Ram N Java

    What is the Session Tracking API?

    The Hypertext Transfer Protocol (HTTP) is inherently stateless. Each request sent by a browser is treated as an entirely isolated interaction, with the server retaining no automatic recollection of previous communications.

    To bridge this gap and create stateful web experiences (such as user authentication, shopping carts, or multi-step questionnaires), the Java Servlet API provides high-level Session Tracking APIs that seamlessly maintain client state across multiple HTTP requests.

    Core Components of the Session Tracking API

    The Servlet specification provides dedicated interfaces and classes designed specifically to simplify session management:

    • HttpSession Interface: The primary interface used by servlets to store user data across requests via key-value attribute pairs.
    • HttpSessionBindingListener: An event listener interface that triggers notifications whenever objects are bound or unbound from a session.
    • HttpSessionEvent & HttpSessionListener: Lifecyle listeners that detect when sessions are created or destroyed across the web application.

    Behind-the-Scenes Session Tracking Techniques

    Under the hood, the Servlet container uses established mechanisms to link incoming requests to the appropriate server-side session:

    • Cookies: The default and most common technique, where a unique session ID (e.g., JSESSIONID) is automatically sent back and forth between browser and server.
    • URL Rewriting: Appends the session identifier directly to the end of each URL when cookies are disabled or unsupported on client browsers.
    • Hidden Form Fields: Incorporates hidden inputs within HTML forms to persist unique transaction IDs between requests.

    Recommended Next Watch

    Continue mastering session management and state tracking with these tutorials:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=jOGg2cLcEic&list=UUhwKlOVR041tngjerWxVccw&index=2

    Click the below Image to Enlarge
    Servlets : Session Tracking API
    Servlets : Session Tracking API
    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • 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
  • Thursday, 22 May 2014

    Servlets : HttpSession Interface

    🚀 Master Java & Servlets with Ram N Java!

    Subscribe to get clear, beginner-friendly tutorials right when they drop.

    🔔 Subscribe to Ram N Java

    What is the HttpSession Interface?

    HTTP is fundamentally a stateless protocol, meaning the web server forgets who you are as soon as a request-response cycle completes. To build real-world web applications like shopping carts, user dashboards, and authentication systems, servers need a way to remember individual clients across multiple visits.

    In Java Servlets, state management across requests is handled via the HttpSession interface. It provides a standardized mechanism to identify a user across more than one page request and store relevant user information on the server.

    How to Obtain an HttpSession Object

    You get a reference to HttpSession directly from the HttpServletRequest object using the getSession() method:

    • request.getSession() or request.getSession(true): Returns the current active session associated with the request. If no session exists for the client, a brand new session is created.
    • request.getSession(false): Returns the existing session if one is currently active. If no session exists, it returns null rather than creating a new one.

    Essential Methods of HttpSession

    • setAttribute(String name, Object value): Binds an object to this session using the specified name.
    • getAttribute(String name): Returns the object bound with the specified name in this session.
    • getId(): Returns a unique identifier string assigned to the specific session (e.g., JSESSIONID).
    • invalidate(): Invalidates and destroys the session, unbinding all objects stored within it (commonly used during user logout).
    • setMaxInactiveInterval(int interval): Specifies the time, in seconds, between client requests before the container will automatically invalidate the session.

    Recommended Next Watch

    Deepen your understanding of Java session tracking with these related tutorials:


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

    Click the below Image to Enlarge
    Servlets : HttpSession Interface
    Servlets : HttpSession Interface
    Servlets : HttpSession Interface
    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Older Posts Home

    Tutorials