Understanding Cookie, Session, and JSP in JavaWeb Applications

1 Session Management Fundamentals

1.1 Session Management Overview

1.1.1 Defining a Session

In web development, a session represents a complete communication cycle between the client and server. The session begins when a user opens a browser and navigates to a website, and terminates when the browser closes or the session expires.

Consider this analogy: when making a phone call to family, if a delivery person knocks on the door, you pause the conversation to answer. Upon returning, the call remains active and you continue speaking seamlessly.

1.1.2 Purpose of Session Management

Session management serves critical functionality in web applications. A shopping cart exemplifies this perfectly—after logging in and adding items to your cart, you can browse various products across the site, and all selected items remain in the cart until checkout.

Additional scenarios where session management proves essential:

  • Forum participation requires authentication; after logging in, the system recognizes your identity across different discussion boards, allowing you to post content with appropriate permissions
  • E-commerce checkout processes maintain cart state across multiple page navigations
  • User preferences and settings persist throughout the browsing experience

These examples demonstrate that sessions facilitate data sharing across multiple requests, enabling stateful interactions in the stateless HTTP protocol environment.

1.1.3 Session Management Categories

JavaEE applications implement two distinct approaches to session management:

Client-Side Session Management

This technique stores shared data directly on the client browser. Each subsequent request transmits this information to the server, enabling data persistence across multiple requests.

Server-Side Session Management

This approach utilizes client-side storage but maintains the actual shared data in server memory. The client stores only a unique session identifier, while the server maintains the corresponding session data mapped to this identifier.

2 Client-Side Session Management: Cookie

2.1 Cookie Fundamentals

2.1.1 What is a Cookie

A cookie is a small text file stored by the browser that contains information about the user's interaction with a website. Cookies constitute a fundamental part of the HTTP protocol, appearing in both request and response headers.

2.1.2 Cookie API Reference

Purpose

Cookies enable websites to remember user preferences and interaction data, reducing redundant server requests by storing this information locally on the client.

Cookie Attributes

Attribute Description Importance
name Cookie identifier Required
value Stored data (ASCII characters only) Required
path URL path scope High
domain Domain scope High
maxAge Lifetime in seconds High
version Cookie specification version Low
comment Description text Low

Technical Constraints

Browser implementations enforce cookie limitations:

  • Maximum 20 cookies per domain
  • Maximum 4KB per cookie
  • Maximum 300 cookies total across all domains

Deletion Behavior

  • Setting maxAge to 0 removes the cookie immediately
  • Omitting maxAge stores the cookie in browser memory only (deleted on browser close)
  • Positive maxAge values persist the cookie as a file on disk (value represents seconds)

2.1.3 Essential Cookie Methods

Creating a Cookie

/**
 * Constructs a Cookie with the specified name and value.
 * 
 * The name must comply with RFC 2109, containing only ASCII alphanumeric
 * characters. It cannot include commas, semicolons, spaces, or begin with $.
 * Once created, the cookie name cannot be modified.
 * 
 * The value can be any content the server chooses to send.
 * After creation, use setValue() to modify the value.
 */
public Cookie(String name, String value) {
    validation.validate(name);
    this.name = name;
    this.value = value;
}

Adding Cookie to Response

/**
 * Adds a cookie to the HTTP response. This method can be invoked
 * multiple times to include several cookies in the response.
 */
public void addCookie(Cookie cookie);

Retrieving Cookies from Request

/**
 * Retrieves all cookies accompanying this request.
 * Returns an array of Cookie objects, or null if no cookies exist.
 */
public Cookie[] getCookies();

2.2 Cookie Path Behavior

2.2.1 Scenario Description

This demonstration creates cookies with specific paths and examines which requests include them when accessing different URL patterns.

2.2.2 Learning Objective

Understanding path matching determines when browsers include cookies in outgoing requests to the server.

2.2.3 Implementation Steps

Step 1: Project Setup

Create a standard JavaWeb project structure.

Step 2: Servlet Implementation

/**
 * Demonstrates cookie path behavior
 * Setup:
 *   demo1: Creates a cookie on the client
 *   demo2: Attempts to retrieve the cookie
 *   demo3: Attempts to retrieve the cookie
 *   
 * Mapping:
 *   demo1: /servlet/PathDemo1
 *   demo2: /servlet/PathDemo2
 *   demo3: /PathDemo3
 */
public class PathDemo1 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Create a cookie with specific name
        Cookie cookie = new Cookie("pathtest", "CookiePathTest");
        // Set cookie to persist for a long duration
        cookie.setMaxAge(Integer.MAX_VALUE);
        // Send cookie to the client
        response.addCookie(cookie);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
/**
 * Retrieves the cookie named "pathtest"
 */
public class PathDemo2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Retrieve all cookies from the request
        Cookie[] cookies = request.getCookies();
        // Iterate through cookie array
        if (cookies != null) {
            for (Cookie c : cookies) {
                if ("pathtest".equals(c.getName())) {
                    response.getWriter().write(c.getValue());
                    return;
                }
            }
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
/**
 * Retrieves the cookie named "pathtest"
 */
public class PathDemo3 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Retrieve all cookies from the request
        Cookie[] cookies = request.getCookies();
        // Iterate through cookie array
        if (cookies != null) {
            for (Cookie c : cookies) {
                if ("pathtest".equals(c.getName())) {
                    response.getWriter().write(c.getValue());
                    return;
                }
            }
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

Step 3: Servlet Mapping Configuration

<!-- Cookie Path Demo Servlet Mappings -->
<servlet>
    <servlet-name>PathDemo1</servlet-name>
    <servlet-class>com.example.web.servlet.PathDemo1</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>PathDemo1</servlet-name>
    <url-pattern>/servlet/PathDemo1</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>PathDemo2</servlet-name>
    <servlet-class>com.example.web.servlet.PathDemo2</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>PathDemo2</servlet-name>
    <url-pattern>/servlet/PathDemo2</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>PathDemo3</servlet-name>
    <servlet-class>com.example.web.servlet.PathDemo3</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>PathDemo3</servlet-name>
    <url-pattern>/PathDemo3</url-pattern>
</servlet-mapping>

Step 4: Deployment

Deploy the application to the servlet container and test the endpoints.

2.2.4 Results Analysis

When accessing the three endpoints, PathDemo1 creates the cookie. PathDemo2 successfully retrieves it, while PathDemo3 receives nothing.

2.2.5 Path Matching Logic

Cookie Identification

A cookie is uniquely identified by the combination of domain + path + name.

In our scenario:

  • Domain remains identical across all endpoints (localhost)
  • Cookie name is consistent (pathtest)
  • Path varies based on the servlet that created the cookie

Since no explicit path was set, the default path equals the directory portion of the request URI.

For PathDemo1 accessed at http://localhost:9090/servlet/PathDemo1, the cookie's default path becomes /servlet/ (the URI directory without the filename).

Path Matching Rule

The browser includes a cookie in requests when:

requestURI.startsWith(cookiePath) == true

In practical terms, more specific paths include cookies in requests to their subdirectories but not vice versa.

Cookie Path Request Path Cookie Sent?
/servlet/ /servlet/PathDemo2 Yes
/servlet/ /PathDemo3 No

3 Server-Side Session Management: HttpSession

3.1 HttpSession Overview

3.1.1 Introduction to HttpSession

HttpSession is a Servlet specification interface implemented by the servlet container (such as Apache Tomcat). It provides a mechanism to identify users across multiple page requests and store user-specific information.

The HttpSession object serves as the session-scoped storage in the Servlet specification's four scope objects:

Scope Object Scope Range Use Case
ServletContext Entire application Data sharing across all components
ServletRequest Current request Data sharing within single request or forward chain
HttpSession Session scope Data sharing across multiple requests

3.1.2 Obtaining HttpSession

The HttpServletRequest interface provides two methods for retrieving session objects:

// Returns existing session or creates new one if none exists
public HttpSession getSession();

// Returns existing session or null if none exists (no creation)
public HttpSession getSession(boolean create);

3.1.3 Common HttpSession Methods

Method Purpose
getAttribute(String name) Retrieves stored attribute
setAttribute(String name, Object value) Stores attribute in session
removeAttribute(String name) Removes attribute from session
invalidate() Invalidates session and clears all data
getMaxInactiveInterval() Returns session timeout in seconds
setMaxInactiveInterval(int seconds) Sets session timeout duration

3.2 HttpSession Quickstart

3.2.1 Scenario

A user submits login credentials via SessionDemo1 servlet, which stores the username in the session. SessionDemo2 servlet retrieves and displays the stored username.

3.2.2 Objectives

This demonstration illustrates session scope for data sharing across multiple requests. Request scope would fail here since each servlet invocation creates a separate request object.

3.2.3 Implementation Mechanics

Despite being a server-side mechanism, HttpSession relies on cookies internally. The server creates a special cookie named JSESSIONID containing a unique session identifier.

When the client makes subsequent requests, the JSESSIONID cookie accompanies each request. The server uses this identifier to locate the corresponding HttpSession object in memory.

3.3 Session Persistence: Passivation and Activation

Passivation (Serialization)

Inactive sessions (approaching expiration) are serialized to disk to conserve memory. This prevents session data loss during high-traffic periods.

Activation (Deserialization)

Previously passivated sessions are loaded back into memory when accessed again.

Triggers for Passivation

  1. Memory pressure: During high traffic, the container prioritizes active sessions and passivates idle ones
  2. Server restart: Ensures session continuity across application restarts

Implementation Requirement

Objects stored in sessions must implement java.io.Serializable to support persistence operations.

4 JSP Technology

4.1 JSP Fundamentals

4.1.1 JSP Definition

JavaServer Pages (JSP) is a Sun specification technology for developing dynamic web resources. JSP functions as a Servlet with HTML templating capabilities, falling under the JSP/Servlet specification umbrella.

4.1.2 Technology Selection Guide

Technology Appropriate Use Limitations
HTML Static content display Cannot embed Java logic or dynamic data
Servlet Business logic implementation Awkward for generating HTML output
JSP Dynamic content display Not suited for complex business logic

4.1.3 Basic JSP Implementation

Creating the JSP File

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>My First JSP</title>
  </head>
  <body>
      This is my first JSP page
  </body>
</html>

Deployment and Testing

Deploy to the servlet container and access the JSP directly via browser.

4.1.4 JSP Internals

Key Insight: Every JSP translates to a Servlet at runtime.

Processing Pipeline

  1. Client sends HTTP request
  2. Container parses the request and locates the JSP file
  3. Jasper compiler (Tomcat's JSP engine) translates JSP to Java source code
  4. Java compiler generates bytecode from source
  5. Container executes the compiled servlet
  6. Response streams back to the client

Generated Servlet Analysis

The translated class extends org.apache.jasper.runtime.HttpJspBase, which itself extends HttpServlet. This inheritance chain confirms JSP's servlet nature.

The JSP's HTML elements translate to out.write() statements with in the generated servlet's _jspService() method, demonstrating that JSP ultimately produces HTML through Java output streams.

JSP excels at presenting dynamic data while maintaining HTML-like syntax for static content, which developers refer to as template elements that establish the page's visual structure.

4.2 JSP Syntax Elements

4.2.1 Scriptlet (Java Code Block)

Syntax: <% Java code here %>

Code within scriptlets becomes method-local variables in the translated servlet.

Example:

<!-- Scriptlet -->
<% out.println("This is a scriptlet");%>
<hr/>

4.2.2 JSP Expression

Syntax: <%= expression %>

Expressions translate to out.print(expression) in the generated code.

Equivalence:

<%="Current time is: " + new java.util.Date()%>
<br/>
<% out.print("Current time is: " + new java.util.Date()); %>

4.2.3 JSP Declaration

Syntax: <%! declarations %>

Declarations become class-level members in the generated servlet.

Example:

<!-- Declaration -->
<%! String message = "Declarations become class members";%>
<%=message%>

4.2.4 JSP Comments

Syntax: <%-- comment text --%>

Comment Type Scope Visibility
HTML comment HTML elements only Visible in browser source
JSP comment All content Hidden from browser

Example:

<%-- This comment won't appear anywhere --%>
<!-- HTML comment visible in source -->

4.2.5 Complete Syntax Demonstration

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>JSP Syntax Examples</title>
</head>
<body>

<!-- Scriptlet -->
<% out.println("Scriptlet output");%>
<hr/>

<!-- Expression -->
<%="Expression output"%><br/>
Equivalent to<br/>
<%out.println("Manual output");%>

<hr/>

<!-- Declaration -->
<%! String text = "Declaration example";%>
<%=text%>

<hr/>

<%-- JSP Comment --%>
<!-- HTML Comment -->

</body>
</html>

4.3 JSP Directives

4.3.1 Page Directive

Attributes Reference:

Attribute Purpose Default
language Scripting language java
extends Parent servlet class (auto-selected)
import Package imports java.lang., javax.servlet., etc.
session Enable HttpSession true
buffer Output buffer size 8kb
errorPage Error handling page none
isErrorPage Exception handling page false
contentType MIME type and charset text/html
pageEncoding File encoding (container-determined)
isELIgnored EL expression evaluation false

Import Examples:

<%@page import="java.util.Date,java.util.UUID"%>
<%@page import="java.util.Date"%>
<%@page import="java.util.UUID"%>

Error Handling Configuration:

<error-page>    
    <exception-type>java.lang.Exception</exception-type>    
    <location>/error.jsp</location>
</error-page>
<error-page>
    <error-code>404</error-code>
    <location>/404.html</location>
</error-page>

4.3.2 Include Directive

Syntax: <%@include file="relativePath" %>

Performs static inclusion at translation time, merging the target file's content before compilation.

4.3.3 Taglib Directive

Syntax: <%@taglib uri="tagLibraryURI" prefix="tagPrefix"%>

Enables use of custom tag libraries. Standard HTML and JSP tags require no declaration.

4.4 JSP Implicit Objects

JSP provides nine pre-declared objects available without explicit declaration:

Object Type Notes
request HttpServletRequest HTTP request data
response HttpServletResponse HTTP response handling
session HttpSession Session-scoped data
application ServletContext Application-wide data
page Object Reference to translated servlet
config ServletConfig Servlet configuration
exception Throwable Error handling (requires isErrorPage=true)
out JspWriter Character output stream
pageContext PageContext Centralized context and scope management

4.5 PageContext Object

4.5.1 Overview

PageContext is unique to JSP environments. It provides:

  • Access to all other implicit objects
  • Operations on all four scope objects
  • Request forwarding and inclusion capabilities

4.5.2 Lifecycle

PageContext instances are local variables scoped to the translated servlet's _jspService() method, existing for the duration of a single JSP page request.

4.5.3 Scope Operations

// Set attribute in specified scope
public abstract void setAttribute(String name, Object value, int scope);

// Retrieve attribute from specified scope
public abstract Object getAttribute(String name, int scope);

// Remove attribute from specified scope
public abstract void removeAttribute(String name, int scope);

// Find attribute across scopes (page → request → session → application)
public abstract Object findAttribute(String name);

// Scope constants
PageContext.PAGE_SCOPE
PageContext.REQUEST_SCOPE
PageContext.SESSION_SCOPE
PageContext.APPLICATION_SCOPE

4.6 Four Scope Objects Comparison

Object Scope Use Case
PageContext Single page only Rarely used due to limited scope
ServletRequest Single request or forward chain Data sharing within request lifecycle
HttpSession Multiple requests from same client User-specific data across interactions
ServletContext Entire application Global application data

5 MVC Architecture in Web Applications

Servlet Role (Controller)

  • Excels at business logic processing
  • Handles request routing and flow control
  • Manages application workflow

JSP Role (View)

  • Specializes in content presentation
  • Renders dynamic HTML output
  • Handles visual layer responsibilities

Model Components

  • Encapsulate business data
  • Represent domain entities
  • Transport data between layers

The MVC pattern separates concerns effectively, with JSP handling presentation and Servlets orchestrating application logic.

6 Student Management System Enhancement

6.1 Requirements

Enhancement 1: View Layer Modernization

Convert existing HTML views to JSP to enable dynamic content rendering and server-side data integration.

Enhancement 2: Persistent Login State

Implement session-based authentication:

  • Initial access presents login interface
  • Successful authentication stores credentials in session
  • Subsequent accesses recognize authenticated users
  • Enable student management operations only for authenticated sessions

6.2 Implementation Approach

Build upon the existing Student Management System architecture, introducing JSP pages for the presentation layer and HttpSession for maintaining authentication state across user interactions.

Tags: JavaWeb Cookie Session JSP servlet

Posted on Wed, 13 May 2026 09:57:33 +0000 by djremiasz