Skip to lesson content
Web Technologies › Level 23
LEVEL 23 · SERVLETS

Java Servlets

Trace servlet lifecycle, request handling and deliberate session changes.

☕ Java web⚙️ Lifecycle👤 Sessions🧪 Lab + MCQs
01

Learning Objectives

Lifecycle

Explain init, service and destroy for one instance.

Handlers

Read input and choose an HTTP response.

Isolation

Separate request-local variables from shared fields.

Sessions

Read, create, invalidate and expire state deliberately.

02

A Container-Managed Component

Who performs the work
Client

Sends an HTTP request.

Container

Maps, initializes and dispatches.

Servlet

Produces the application outcome.

Response

Returns metadata and a body.

03

Mapping and Context Paths

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;

@WebServlet("/study")
public class StudyServlet extends HttpServlet {
    // Add doGet/doPost handlers inside this class.
}
04

Initialization: Prepare One Instance

// Inside a servlet class; illustrative lifecycle hooks:
@Override
public void init() {
    getServletContext().log("Study servlet initialized");
}

@Override
public void destroy() {
    getServletContext().log("Study servlet destroyed");
    // Release resources that this component actually owns.
}
05

Service and HTTP Handlers

Lifecycle of one instance
Create

Container instantiates the component.

Initialize

Prepare before handling requests.

Service

Handle many requests.

Destroy

Finish this instance’s lifecycle.

06

Destruction and Resource Ownership

Owned resources

Close what the component is responsible for.

In-flight work

Real concurrency needs separate verification.

Replacement

Create a new component instance.

Session lifetime

A session and a servlet have different lifetimes.

07

Request Parameters and Repeated Values

// Illustrative validation fragment inside doPost:
String[] values = request.getParameterValues("topic");
if (values == null || values.length != 1) {
    response.sendError(400, "One topic is required");
    return;
}
String topic = values[0];
if (!java.util.Set.of("html", "servlets", "jsp").contains(topic)) {
    response.sendError(400, "Unknown topic");
    return;
}
// Validate all remaining input before changing session state.
08

Response Status, Encoding and Commitment

// Illustrative doGet handler inside a servlet class:
@Override
protected void doGet(jakarta.servlet.http.HttpServletRequest request,
                     jakarta.servlet.http.HttpServletResponse response)
        throws java.io.IOException {
    response.setContentType("text/plain; charset=UTF-8");
    response.getWriter().println("Read-only study endpoint");
}
09

Request-Local Variables and Shared Fields

// Avoid: private String currentLearner;
// Prefer request-local data inside a handler:
String learner = request.getParameter("learner");
// Validate learner, then construct this request’s result locally.

Local

One invocation’s input and result.

Request attribute

Carry a model through a dispatch.

Session

Deliberately associate state with a client session.

Shared dependency

Choose lifetime and concurrency controls.

10

Read a Session Without Creating One

// Illustrative read in doGet:
jakarta.servlet.http.HttpSession session = request.getSession(false);
Object preference = session == null ? null
        : session.getAttribute("studyPreference");
// Render a controlled anonymous or accepted-preference result.
11

Create and Update Session Attributes Deliberately

// Illustrative fragment AFTER complete input validation:
jakarta.servlet.http.HttpSession session = request.getSession();
session.setAttribute("studyPreference", acceptedPreference);
// acceptedPreference is a bounded application value prepared earlier.
Two client associations
Client A

Mock association to session A.

Session A

A’s accepted study preference.

Client B

Separate mock association.

Session B

B’s accepted study preference.

12

Invalidation, Expiry and Stale Associations

// Illustrative logout handler logic:
jakarta.servlet.http.HttpSession session = request.getSession(false);
if (session != null) {
    session.invalidate();
}
// Return a deliberate logout outcome; do not create a new session.
13

Sessions Are Not a Complete Security System

Identity

Verify who the caller is.

Authorization

Check the requested protected action.

CSRF

Protect cookie-authenticated mutations.

Output

Encode for the actual destination context.

14

Forward, Redirect and Post-Redirect-Get

// Illustrative MVC flow before response commitment:
request.setAttribute("study", acceptedModel);
request.getRequestDispatcher("/WEB-INF/views/study.jsp")
       .forward(request, response);

// A different response choice for an accepted POST:
// Redirect to a server-controlled, context-aware read URL.
// Do not forward and redirect the same response.
15

Separate Model Tests from Container Tests

Lifecycle

Initialize once, service repeatedly, stop after destroy.

Isolation

A and B keep separate accepted preferences.

Rejections

Validation failures leave session state unchanged.

Integration

Verify the actual runtime independently.

16

Premium Visualizer — Servlet Lifecycle and Request

Trace one accepted study-preference POST through mapping, initialization, handler validation, session association and response. The approved five-stage player explains a local model; it does not run a Java servlet.

SERVLET LIFECYCLE AND REQUEST TRACE
Step 1 of 5
STEP 01

Find the mapped servlet

The application-relative path selects the component.

POST /study

What is happening?

Unknown paths stop at routing. This player follows an accepted POST for one mock client.

17

Premium Interactive — Servlet Lifecycle and Session Lab

Idle. Synchronous JavaScript model; no servlet container is running.

Servlet and session state · public teaching data

Current request trace

No request yet.

Response metadata and literal body

No response yet.

Safe text preview

No preview yet.

Lifecycle log · last 30 events

18

Debugging — Find the First Wrong Boundary

Mapping

Check context path and annotation/descriptor mapping.

Parameters

Inspect missing, repeated and invalid values before mutation.

Sessions

Distinguish absent, valid and stale associations.

Shared fields

Look for request data stored on the servlet instance.

19

Interview Questions — Flip to Explain

QUESTION

Who calls init, service and destroy?

Click or press Enter to explain
ANSWER

The servlet container manages the lifecycle and invokes those callbacks.

QUESTION

Does init run for every request?

Click or press Enter to explain
ANSWER

No. It initializes that instance before servicing; a replacement instance has its own lifecycle.

QUESTION

Why override doGet or doPost instead of service in ordinary HTTP handlers?

Click or press Enter to explain
ANSWER

HttpServlet already dispatches HTTP methods; handlers express the application behavior without replacing that dispatcher.

QUESTION

Why avoid a mutable currentLearner instance field?

Click or press Enter to explain
ANSWER

One servlet instance can handle concurrent requests, so one caller can overwrite another’s data.

QUESTION

What is getSession(false) useful for?

Click or press Enter to explain
ANSWER

Reading an existing valid session without allocating a new session when there is none.

QUESTION

Does an existing session prove authentication?

Click or press Enter to explain
ANSWER

No. Identity and authorization require separate trustworthy application checks.

QUESTION

What happens after invalidation?

Click or press Enter to explain
ANSWER

The session is no longer valid; later requests may have no current session, and the old object must not be reused as valid.

QUESTION

Does this local lab verify actual cookie or container behavior?

Click or press Enter to explain
ANSWER

No. It checks a synchronous JavaScript model; real deployment, expiry and concurrency require integration tests.

20

MCQ Practice — Explain Servlet Decisions

PRACTICE

1. Who creates request and response objects for a servlet?

PRACTICE

2. When does init run for an instance?

PRACTICE

3. Which is a normal read handler?

PRACTICE

4. Where should one request’s learner input normally be kept?

PRACTICE

5. Which session call avoids creating a session?

PRACTICE

6. When does an invalid POST create a session in this lab?

PRACTICE

7. Which outcome is used for an unsupported mapped method?

PRACTICE

8. What happens to a destroyed modeled instance?

PRACTICE

9. Does an anonymous GET /study allocate a session?

PRACTICE

10. What does the Expire button demonstrate?

PRACTICE

11. Which value proves authorization by itself?

PRACTICE

12. Do synchronous model tests prove real servlet concurrency safety?

21

Extra Practice — Predict State Transitions

Anonymous read

GET /study for A. Expect init once, 200 anonymous and zero sessions.

Accepted save

POST /study, Demo learner/html. Expect one session, saved preference and another service call.

Other client

Switch to B and GET. Expect anonymous; A’s session remains unchanged.

Rejected input

For A, POST a one-character label or repeated-value shape. Expect 400 and unchanged session data.

Logout twice

POST /logout twice for A. Expect 200 both times and no new session.

Stale association

Save, expire, then GET. Expect anonymous without recreation; valid POST then creates a new mock ID.

Destroy and replace

Destroy, then GET: 503 without a service call. Create a new instance and GET: init once for the new generation.

Literal text

Save learner <Demo> and a valid topic. Expect literal text, JSON source and no injected element.

22

Quick Revision

Container: Manages lifecycle and dispatch.
Mapping: Relative to the application context.
Init: Once for a successfully initialized instance.
Service: Repeated request processing.
Destroy: Cleanup for the retiring instance.
Local data: Avoid per-request instance fields.
Validation: Reject before session mutation.
Read session: getSession(false) avoids allocation.
Invalidate: End the valid session association.
Integration: Verify real runtime separately.
23

Glossary — Flip to Learn

TERM

Servlet

Click to see meaning
DEFINITION

Servlet

A container-managed Java request-processing component.

TERM

HttpServlet

Click to see meaning
DEFINITION

HttpServlet

A servlet base class with HTTP method dispatch and handlers.

TERM

Context path

Click to see meaning
DEFINITION

Context path

The application’s path prefix within the server.

TERM

Servlet mapping

Click to see meaning
DEFINITION

Servlet mapping

A URL pattern associated with a component.

TERM

Initialization

Click to see meaning
DEFINITION

Initialization

Preparation before an instance services requests.

TERM

Response commitment

Click to see meaning
DEFINITION

Response commitment

The point at which response metadata/output has been sent and cannot be freely changed.

TERM

Request-local variable

Click to see meaning
DEFINITION

Request-local variable

A value local to one handler invocation.

TERM

HttpSession

Click to see meaning
DEFINITION

HttpSession

Container-managed state associated with a client session.

TERM

Invalidation

Click to see meaning
DEFINITION

Invalidation

Ending a session’s validity and unbinding its attributes.

TERM

Post-Redirect-Get

Click to see meaning
DEFINITION

Post-Redirect-Get

A flow that follows an accepted POST with a redirect to a GET resource.

24

Final Challenge — Specify a Study Servlet

25

Level 23 Complete?

Explain lifecycle callbacks and HTTP dispatch, reproduce both mock clients’ independent preferences, and show that invalid input, logout and expiry do not accidentally create sessions. Identify the real-runtime checks this model cannot perform. Completion is a local study marker.