Servlet State and Filters

Back

Loading concept...

🏨 The Grand Hotel of Web Requests

Welcome to Jakarta EE Servlets - where every web request is a guest checking into our magical hotel!


The Story Begins…

Imagine you run a Grand Hotel. Every visitor (web request) who walks through your doors needs:

  • A welcome desk to check them in (Servlet Context)
  • Hallways to guide them to rooms (Request Dispatching)
  • Security guards checking everyone (Filters)
  • A guest card remembering who they are (Sessions & Cookies)

Let’s explore each room of our hotel!


🏛️ Servlet Context: The Hotel’s Memory

What Is It?

The Servlet Context is like the hotel’s main office that remembers EVERYTHING about the hotel itself - not about individual guests, but about the whole building.

Simple Example:

// Store hotel-wide info
context.setAttribute("hotelName",
    "Grand Jakarta Hotel");

// Any room (servlet) can read it
String name = (String)
    context.getAttribute("hotelName");

Why Does It Matter?

  • One context for the entire application
  • Shared storage all servlets can access
  • Lives forever (until server stops)
graph TD A["Servlet Context"] --> B["Servlet 1"] A --> C["Servlet 2"] A --> D["Servlet 3"] style A fill:#667eea,color:#fff

Real Life: Think of it as the hotel’s bulletin board - any employee can read or post messages there!


🚪 Request Dispatching: The Bellhop Service

What Is It?

When a guest needs to visit multiple rooms, the bellhop (RequestDispatcher) takes them there!

Simple Example:

// Get the bellhop for a destination
RequestDispatcher bellhop =
    request.getRequestDispatcher(
        "/another-room.jsp"
    );

// Take the guest there
bellhop.forward(request, response);

Two Ways to Dispatch

Method What Happens
forward() Bellhop takes guest, guest never returns
include() Bellhop fetches something, brings it back

↔️ Forward vs Redirect: Two Different Trips

The Big Difference

Forward = Internal hotel transfer

  • Guest stays in the hotel
  • Address bar shows ORIGINAL room
  • Fast! (one trip)

Redirect = Guest leaves and comes back

  • Guest walks outside, re-enters
  • Address bar shows NEW room
  • Slower (two trips)
// FORWARD - internal transfer
request.getRequestDispatcher("/page2")
    .forward(request, response);

// REDIRECT - go outside, come back
response.sendRedirect("/page2");
graph TD subgraph Forward A1["Request"] --> B1["Servlet A"] B1 --> C1["Servlet B"] C1 --> D1["Response"] end subgraph Redirect A2["Request 1"] --> B2["Servlet A"] B2 --> C2["Browser"] C2 --> D2["Request 2"] D2 --> E2["Servlet B"] end

When to Use What?

  • Forward: Processing data, staying on same task
  • Redirect: After form submission (prevents duplicate)

🛡️ Servlet Filters: The Security Guards

What Is It?

Filters are like security guards at the hotel entrance. They check every guest BEFORE they reach their room and AFTER they leave.

Simple Example:

public class SecurityFilter
    implements Filter {

    public void doFilter(
        ServletRequest request,
        ServletResponse response,
        FilterChain chain) {

        // Check guest BEFORE
        System.out.println("Checking in...");

        // Let guest through
        chain.doFilter(request, response);

        // Check guest AFTER
        System.out.println("Checking out...");
    }
}

Common Filter Uses

  • 🔐 Authentication - Is this guest allowed?
  • 📝 Logging - Record who visited
  • 🗜️ Compression - Pack their luggage smaller
  • 🔤 Encoding - Translate languages

⛓️ Filter Chains: Multiple Security Checkpoints

What Is It?

Multiple filters work together in a chain - like passing through several security checkpoints!

graph LR A["Request"] --> B["Filter 1"] B --> C["Filter 2"] C --> D["Filter 3"] D --> E["Servlet"] E --> D D --> C C --> B B --> F["Response"] style E fill:#4ECDC4,color:#fff

How It Works:

  1. Request enters Filter 1
  2. Filter 1 calls chain.doFilter() → goes to Filter 2
  3. Filter 2 calls chain.doFilter() → goes to Filter 3
  4. Filter 3 calls chain.doFilter() → reaches Servlet
  5. Response travels back through ALL filters!

Configure in web.xml:

<filter-mapping>
    <filter-name>LogFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>AuthFilter</filter-name>
    <url-pattern>/secure/*</url-pattern>
</filter-mapping>

👂 Servlet Listeners: The Hotel Staff

What Is It?

Listeners are like attentive hotel staff who notice when things happen and respond automatically!

Types of Listeners

Listener Watches For
ServletContextListener Hotel opens/closes
HttpSessionListener Guest checks in/out
ServletRequestListener Each visit starts/ends

Simple Example:

@WebListener
public class HotelStaff
    implements HttpSessionListener {

    public void sessionCreated(
        HttpSessionEvent event) {
        System.out.println(
            "New guest checked in!");
    }

    public void sessionDestroyed(
        HttpSessionEvent event) {
        System.out.println(
            "Guest checked out!");
    }
}

Real Life: Like a doorman who says “Welcome!” every time someone enters!


🎫 Session Management: The Guest Card

What Is It?

HTTP is forgetful - it doesn’t remember guests between visits. Sessions are like VIP guest cards that help the hotel remember!

Simple Example:

// Get guest's VIP card
HttpSession session =
    request.getSession();

// Write on their card
session.setAttribute("name", "Alice");
session.setAttribute("vipLevel", 5);

// Read from their card later
String name = (String)
    session.getAttribute("name");

Session Lifecycle

graph TD A["First Visit"] --> B["Create Session"] B --> C["Store Data"] C --> D["Guest Returns"] D --> E["Read Data"] E --> F["Timeout or Logout"] F --> G["Session Destroyed"] style B fill:#FF6B6B,color:#fff style G fill:#95a5a6,color:#fff

Important Settings

// Session expires after 30 minutes
session.setMaxInactiveInterval(1800);

// Manually destroy session
session.invalidate();

🍪 Cookie Handling: The Loyalty Stamps

What Is It?

Cookies are like loyalty stamps the hotel gives guests. The guest keeps them in their wallet (browser) and shows them on every visit!

Creating a Cookie:

// Create a stamp
Cookie cookie = new Cookie(
    "favoriteRoom", "302"
);

// Set how long it lasts
cookie.setMaxAge(60 * 60 * 24); // 1 day

// Give it to the guest
response.addCookie(cookie);

Reading Cookies:

Cookie[] stamps = request.getCookies();

if (stamps != null) {
    for (Cookie stamp : stamps) {
        if ("favoriteRoom"
            .equals(stamp.getName())) {
            String room = stamp.getValue();
        }
    }
}

Sessions vs Cookies

Feature Session Cookie
Stored Server Browser
Size Large OK Max 4KB
Security Safer Visible
Lifetime Until timeout Can be forever

Pro Tip: Sessions use a cookie (JSESSIONID) to track which guest card belongs to whom!


🎯 Putting It All Together

Here’s how our hotel handles a typical VIP guest:

graph TD A["Guest Arrives"] --> B["Security Filter"] B --> C["Logging Filter"] C --> D["Servlet Context Check"] D --> E{Has Session?} E -->|No| F["Create Session"] E -->|Yes| G["Load Session"] F --> H["Check Cookies"] G --> H H --> I["Dispatch to Room"] I --> J["Forward/Redirect"] J --> K["Response with Cookies"]

🏆 Key Takeaways

  1. Servlet Context = Hotel’s shared memory
  2. Request Dispatching = Internal transfers
  3. Forward = Stay inside, Redirect = Go outside
  4. Filters = Security checkpoints
  5. Filter Chains = Multiple checkpoints in order
  6. Listeners = Attentive staff watching for events
  7. Sessions = VIP guest cards (server-side)
  8. Cookies = Loyalty stamps (browser-side)

Now you understand how the Grand Hotel of Servlets works! Every request is a guest, and you know exactly how to welcome, track, and serve them. 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.