Servlet Request Handling

Loading concept...

🍽️ Servlet Request Handling: Your Restaurant Kitchen Analogy

Imagine you run a restaurant. Customers (browsers) walk in and place orders (HTTP requests). Your kitchen (servlet container) receives these orders, your chefs (servlets) cook the meals (process requests), and waiters bring back the food (HTTP responses).

This is exactly how Jakarta Servlets work!


🏠 Jakarta Servlet Overview

What is a Servlet?

A servlet is like a chef in your restaurant kitchen. It waits for orders, prepares food, and sends it out.

In computer terms:

  • Customer walks in → Browser sends HTTP request
  • Chef receives order → Servlet receives request
  • Chef cooks food → Servlet processes data
  • Waiter delivers → Server sends response
@WebServlet("/hello")
public class HelloServlet
    extends HttpServlet {

    protected void doGet(
        HttpServletRequest req,
        HttpServletResponse res) {
        // Cook the response!
    }
}

The @WebServlet("/hello") is like putting a sign on your chef’s station saying “I handle hello orders!”


🔄 Servlet Lifecycle

Every chef has a career lifecycle. Servlets do too!

The Three Big Moments

graph TD A["🎓 init - Chef gets hired"] --> B["🍳 service - Chef cooks orders"] B --> C["👋 destroy - Chef retires"] B --> B

1. init() - The Hiring Day 🎓

Called once when the servlet is first created. Like a chef’s first day at work.

public void init() {
    // Set up your kitchen!
    // Load recipes, prepare tools
    System.out.println("Chef ready!");
}

2. service() - Cooking Time 🍳

Called every time a customer orders. This is where the real work happens!

protected void service(
    HttpServletRequest req,
    HttpServletResponse res) {
    // Handle the order!
}

Fun fact: For HTTP, this automatically calls doGet(), doPost(), etc. based on the order type!

3. destroy() - Retirement Day đź‘‹

Called once when the servlet shuts down. Time to clean up!

public void destroy() {
    // Close connections
    // Save data
    System.out.println("Chef retired!");
}

⚙️ Servlet Configuration

How to Tell Your Chef What to Do

There are two ways to configure servlets:

Method 1: Annotations (Modern Way) ✨

Put instructions right on the chef!

@WebServlet(
    name = "OrderServlet",
    urlPatterns = {"/order", "/menu"},
    loadOnStartup = 1
)
public class OrderServlet
    extends HttpServlet {
    // Your code here
}
Attribute Meaning
name Chef’s nickname
urlPatterns What orders they handle
loadOnStartup Start cooking immediately?

Method 2: web.xml (Classic Way) 📜

Write instructions in a separate file:

<servlet>
    <servlet-name>OrderServlet</servlet-name>
    <servlet-class>
        com.app.OrderServlet
    </servlet-class>
    <init-param>
        <param-name>maxOrders</param-name>
        <param-value>100</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>OrderServlet</servlet-name>
    <url-pattern>/order</url-pattern>
</servlet-mapping>

Init Parameters

Like giving your chef special instructions:

String max = getInitParameter("maxOrders");
// Returns "100"

🌍 Servlet Context Parameters

Restaurant-Wide Settings

What if ALL chefs need to know something? Use context parameters!

Think of it as posting a notice on the kitchen wall that everyone can read.

In web.xml:

<context-param>
    <param-name>restaurantName</param-name>
    <param-value>Jakarta Bistro</param-value>
</context-param>

In your servlet:

ServletContext ctx =
    getServletContext();

String name = ctx
    .getInitParameter("restaurantName");
// Returns "Jakarta Bistro"

Context vs Init Parameters

Type Scope Analogy
Init Param One servlet only Chef’s personal recipe
Context Param Entire app Restaurant policy

📥 HttpServletRequest

The Customer’s Order Slip

When someone orders, you get ALL their information:

graph TD A["Browser Request"] --> B["HttpServletRequest"] B --> C["URL &amp; Path"] B --> D["Headers"] B --> E["Parameters"] B --> F["Cookies"] B --> G["Session"]

Getting URL Information

// Customer came to:
// http://food.com/menu?item=pizza

req.getRequestURI();
// Returns: /menu

req.getQueryString();
// Returns: item=pizza

req.getContextPath();
// Returns: /food (app name)

Getting Parameters

Parameters are like order details:

// URL: /order?food=burger&qty=2

String food = req.getParameter("food");
// Returns: "burger"

String qty = req.getParameter("qty");
// Returns: "2"

// For multiple values (checkboxes):
String[] toppings =
    req.getParameterValues("topping");

Reading Headers

Headers are like sticky notes on the order:

String browser =
    req.getHeader("User-Agent");
// Shows what browser they use

String contentType =
    req.getContentType();
// What format is the data?

Common Request Methods

Method What it gets
getMethod() GET, POST, etc.
getRemoteAddr() Customer’s IP
getCookies() All cookies
getSession() User’s session

📤 HttpServletResponse

Sending Food Back to the Customer

The response is your delivery tray!

Setting Up the Response

// Tell them what kind of food
res.setContentType("text/html");

// Set the character encoding
res.setCharacterEncoding("UTF-8");

// Get the tray (writer) to put food on
PrintWriter out = res.getWriter();

out.println("<h1>Here's your order!</h1>");
out.println("<p>Enjoy your burger!</p>");

Adding Headers

Put notes on the tray:

res.setHeader("X-Chef", "Mario");
res.addHeader("X-Special", "Extra love");

// No caching (fresh food only!)
res.setHeader("Cache-Control",
    "no-cache");

Setting Cookies

Give them a loyalty card:

Cookie card = new Cookie(
    "customer", "john123"
);
card.setMaxAge(3600); // 1 hour
res.addCookie(card);

Redirecting

Send them to another restaurant:

res.sendRedirect("/new-location");

🚦 Response Status Codes

How to Tell Customers What Happened

Status codes are like hand signals to your customer:

graph TD A["Status Codes"] --> B["2xx ✅ Success"] A --> C["3xx 🔄 Redirect"] A --> D["4xx ❌ Client Error"] A --> E["5xx 💥 Server Error"]

The Most Important Codes

Code Meaning Restaurant Analogy
200 OK “Here’s your food!”
201 Created “New dish added to menu!”
301 Moved Permanently “We moved locations forever”
302 Found (Redirect) “Try the other counter”
400 Bad Request “I can’t read your order”
401 Unauthorized “Show your member card”
403 Forbidden “Staff only area!”
404 Not Found “We don’t serve that”
500 Server Error “Kitchen fire!”

Setting Status in Code

// Everything's great!
res.setStatus(200);

// Oops, we don't have that
res.sendError(404, "Dish not found");

// Kitchen problems
res.sendError(500,
    "Chef burnt the food");

Quick Trick

// These are the same:
res.setStatus(
    HttpServletResponse.SC_OK);
res.setStatus(200);

🏷️ Request Attributes

Passing Notes Between Chefs

Sometimes one chef needs to tell another chef something. That’s what attributes are for!

Unlike parameters (which come from the customer), attributes are notes between your kitchen staff.

Setting and Getting Attributes

// Chef 1 writes a note:
req.setAttribute("specialSauce",
    "secret recipe");

// Chef 2 reads the note:
String sauce = (String)
    req.getAttribute("specialSauce");

Forwarding with Attributes

This is super useful when passing data to another servlet:

// In FirstServlet:
req.setAttribute("order", orderObject);

RequestDispatcher rd =
    req.getRequestDispatcher("/cook");
rd.forward(req, res);

// In CookServlet:
Order order = (Order)
    req.getAttribute("order");

Attributes vs Parameters

Feature Parameter Attribute
Source Client (browser) Server code
Type Always String Any Object
Set by URL or form Your code
Use case User input Sharing data

Removing Attributes

Clean up when done:

req.removeAttribute("specialSauce");

🎯 Putting It All Together

Here’s a complete example showing everything:

@WebServlet("/order")
public class OrderServlet
    extends HttpServlet {

    private String restaurantName;

    // 1. INIT - Setup
    public void init() {
        restaurantName =
            getServletContext()
            .getInitParameter("name");
    }

    // 2. SERVICE - Handle orders
    protected void doGet(
        HttpServletRequest req,
        HttpServletResponse res)
        throws IOException {

        // Read the order
        String item =
            req.getParameter("item");

        // Prepare response
        res.setContentType("text/html");
        res.setStatus(200);

        // Send it!
        PrintWriter out =
            res.getWriter();
        out.println("<h1>" +
            restaurantName + "</h1>");
        out.println("<p>You ordered: "
            + item + "</p>");
    }

    // 3. DESTROY - Cleanup
    public void destroy() {
        System.out.println("Goodbye!");
    }
}

🌟 Key Takeaways

  1. Servlets are like chefs - they receive orders and send back food
  2. Lifecycle is simple: init → service → destroy
  3. Configuration can be annotations or XML
  4. Request carries everything about the customer’s order
  5. Response is how you send back the food
  6. Status codes tell customers what happened
  7. Attributes are notes between your server code

You now understand how web requests flow through Jakarta Servlets! 🎉


đź’ˇ Remember: Every time you visit a website, somewhere a servlet (or something similar) is cooking up your response. You now know exactly how that kitchen works!

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.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive - Premium Content

Please sign in to view this interactive content and start learning.

Upgrade to Premium to unlock full access to all interactive content.

Stay Tuned!

Interactive content is coming soon.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Cheatsheet - Premium Content

Please sign in to view this cheatsheet and start learning.

Upgrade to Premium to unlock full access to all cheatsheets.

Stay Tuned!

Cheatsheet is coming soon.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Quiz - Premium Content

Please sign in to view this quiz and test your knowledge.

Upgrade to Premium to unlock full access to all quizzes.

Stay Tuned!

Quiz is coming soon.

Flashcard Preview

Flashcard - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Flashcard - Premium Content

Please sign in to view flashcards and reinforce your learning.

Upgrade to Premium to unlock full access to all flashcards.

Stay Tuned!

Flashcards are coming soon.