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:
- forward(): Complete transfer of request execution to another resource. The client is unaware, and the browser URL remains the same.
- include(): Merges the content of a target resource into the calling servlet's response stream.
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:
- Creation:
Cookie c = new Cookie("key", "val"). - Configuration:
c.setMaxAge(int seconds)configures expiration. - Retrieval: Read cookies on subsequent requests using
request.getCookies().
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:
- JSESSIONID: A unique session ID token generated by the server. It is sent to the client browser as a cookie to link requests to the correct session.
- State Storage: Uses
setAttribute()andgetAttribute()to save and read objects. - Termination:
session.invalidate()destroys the session and releases its resources.
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.