Web applications are stateless by default. In this module, we will explore RequestDispatcher forwarding and track user state using Cookies and HttpSession.

2.1. RequestDispatcher Interface (forward vs. include)

Definition: The RequestDispatcher interface provides the ability to dispatch client requests to another resource (such as a servlet or JSP) on the server.

Core Working Principles:

5-Marks Exam Scoring Points
  • Obtained using request.getRequestDispatcher().
  • forward() transfers execution; include() merges layouts.
  • Server-side redirection; fast execution with no extra network roundtrips.
  • Maintains request attributes across components.

2.2. Cookie-Based Session Tracking

Definition: A Cookie is a small text file containing a key-value pair that a web server sends to a browser. The browser saves the cookie on the client's hard drive and sends it back with every request.

Core Working Principles:

Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for (Cookie c : cookies) {
        if ("user".equals(c.getName())) {
            String username = c.getValue();
        }
    }
}
5-Marks Exam Scoring Points
  • Cookies store state data directly on the client's device.
  • Created in Java using Cookie class, sent using response.addCookie().
  • Read on requests using request.getCookies() array.
  • Limited to simple text strings and vulnerable to tampering by users.

2.3. HttpSession Lifecycle Management

Definition: HttpSession is an interface used to bind user sessions and store state information securely in server memory.

Core Working Principles:

5-Marks Exam Scoring Points
  • Stores session attributes securely in the server's memory, unlike client-side cookies.
  • The container tracks sessions automatically using the JSESSIONID cookie.
  • session.isNew() returns true if the session was just created for the client.
  • session.invalidate() destroys session data immediately; used for logging out.