Java Servlets: Server-Side Request Handling with a Worked HTTP Trace

Follow one request from servlet mapping to doPost(), validate its inputs, calculate a score, and return JSON. Then test error paths and concurrent requests.

KnowledgeGate Team

Exam prep & CS education

Updated 23 Nov 20266 min read
Java Servlets: Server-Side Request Handling with a Worked HTTP Trace

Servlet request handling becomes easier when every layer is traced in order: URL mapping, service() dispatch, parameter parsing, validation, response status, and concurrency. For POST /practice/score?set=java-servlets with correct=18, wrong=4, and total=22, the synthetic rule finalScore = (2 x correct) - wrong produces (2 x 18) - 4 = 32. The Servlet contract is separate from that invented scoring rule. Start with Coding & DSA Courses for Placements if the Java web context is unfamiliar.

Servlet in the HTTP request-response path

A servlet is a container-managed Java component that handles requests and builds responses. For HTTP work, it normally extends HttpServlet. On each dispatch, the container supplies an HttpServletRequest and HttpServletResponse. Jakarta Servlet defines this contract, while a compatible container implements it.

POST /practice/score?set=java-servlets reaches the container. The context path /practice selects the web application, and the servlet path /score matches @WebServlet("/score"). Filters may wrap the request or response before HttpServlet.service() dispatches to doPost(). The servlet can be long-lived, while request and response objects belong to each invocation. Review Object Oriented Technology Explained: Four Pillars in Java if class and instance basics are unclear.

Separate servlet lifecycle from per-request method dispatch

The Jakarta Servlet 6.1 specification defines the order: load the class, create an instance, call init() before service, invoke service(request, response) for requests, and call destroy() when removing the servlet. Construction and init() are not per-request events.

HttpServlet.service() examines the method and routes POST to doPost(), GET to doGet(), and other supported methods to their handlers. Override the required doXxx methods instead of rebuilding dispatch in service().

A container may run concurrent requests through the same servlet instance. Parameters and local variables belong to each invocation. Mutable instance fields can be shared by request threads, which creates a race.

QuizScoreServlet: a complete servlet example

Request-specific values stay local, and the static helper stores no instance state. Because getParameter() returns text, each value needs parsing and validation. Set the JSON content type, UTF-8 encoding, and status before getWriter() writes the body. The +2/-1 rule and total <= 1000 bound are invented for this trace, not Servlet or exam rules.

java
import java.io.IOException;

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

@WebServlet("/score")
public final class QuizScoreServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Use POST");
    }

    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        String correctText = request.getParameter("correct");
        String wrongText = request.getParameter("wrong");
        String totalText = request.getParameter("total");

        if (correctText == null || wrongText == null || totalText == null) {
            badRequest(response, "missing score field");
            return;
        }

        try {
            int correct = Integer.parseInt(correctText);
            int wrong = Integer.parseInt(wrongText);
            int total = Integer.parseInt(totalText);

            if (correct < 0 || wrong < 0 || total < 1 || total > 1000
                    || correct > total || wrong > total || correct + wrong > total) {
                badRequest(response, "invalid score values");
                return;
            }

            int earned = correct * 2;
            int deduction = wrong;
            int finalScore = earned - deduction;

            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().printf(
                "{\"correct\":%d,\"wrong\":%d,\"total\":%d," +
                "\"earned\":%d,\"deduction\":%d,\"finalScore\":%d}",
                correct, wrong, total, earned, deduction, finalScore);
        } catch (NumberFormatException exception) {
            badRequest(response, "score fields must be integers");
        }
    }

    private static void badRequest(HttpServletResponse response,
                                   String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().printf("{\"error\":\"%s\"}", message);
    }
}

Trace the exact POST from bytes to the 200 JSON response

The request is:

http
POST /practice/score?set=java-servlets HTTP/1.1
Host: example.test
Content-Type: application/x-www-form-urlencoded

correct=18&wrong=4&total=22

Event

Observed value

Result

Request method

POST

Continue through HTTP dispatch

Context path

/practice

Select the web application

Servlet path

/score

Match @WebServlet("/score")

Query parameter

set is "java-servlets"

Available to the request, but not used in scoring

Form parameters

"18", "4", "22"

Read as text

Method dispatch

service() sees POST

Select doPost()

Parsing

18, 4, 22

Produce integers

Validation

18 + 4 = 22, not greater than 22

Accept the values

Earned

18 x 2 = 36

Set earned to 36

Deduction

4 x 1 = 4

Set deduction to 4

Final score

36 - 4 = 32

Set finalScore to 32

The server returns status 200, media type application/json, UTF-8 encoding, and the exact compact body {"correct":18,"wrong":4,"total":22,"earned":36,"deduction":4,"finalScore":32}.

Diagram tracing the worked POST /practice/score request from the client through the servlet container mapping and service() dispatch into doPost(), ending in the 200 JSON response with finalScore 32.

Keep parameters, attributes, scopes and concurrent requests separate

Value kind

Exact example

Lifetime or visibility

Use

Request parameter

correct -> "18"

Client-supplied text for this request

Read input

Local variable

finalScore -> 32

This invocation only

Compute safely

Request attribute

finalScore -> Integer 32

This request and a forward

Pass server-side data

Session attribute

attempts: 6 -> 7

Requests in one session

Retain user-session state

Servlet-context attribute

courseName -> "Java"

Shared across the web application

Share application data

Request attributes stay within one dispatch chain, sessions span one user conversation, and context attributes are application-wide. If R2 sends correct=15, wrong=5, total=22, it gets earned 30, deduction 5, and finalScore 25 while R1 gets 32. Invocation-local variables do not collide on the shared servlet instance.

Adding private int finalScore; makes the value shared. Concurrent writes can leave a later read seeing 32 or 25; no result is guaranteed. A deployment also need not use exactly one servlet instance.

Diagram of one shared QuizScoreServlet instance serving two concurrent requests on separate threads, each computing its own local finalScore of 32 and 25 without touching shared state.

Error branches, response commitment, and forwarding

Invalid input and error branches

The code has deterministic error branches:

  • Missing total returns 400 with {"error":"missing score field"}.

  • correct=eighteen&wrong=4&total=22 returns 400 with {"error":"score fields must be integers"}.

  • correct=18&wrong=7&total=22 fails because 18 + 7 = 25 > 22, then returns 400 with {"error":"invalid score values"}.

  • A GET reaches doGet() and calls sendError(405, "Use POST"). The container controls the error page body.

Response commitment

Set status, content type, and encoding before committing body bytes. After commitment, headers cannot change and forwarding is too late. The contract defines that boundary, not a fixed container buffer size.

Forward versus redirect

RequestDispatcher performs a server-side forward. request.setAttribute("finalScore", 32) followed by a forward to /WEB-INF/result.jsp keeps the same request and attributes. response.sendRedirect("/practice/result?id=R42") makes the browser start a new request, so the previous request attribute is lost.

How exams and interviews test servlet request handling

Exam questions usually ask you to order the lifecycle, route POST to doPost(), classify a value by scope, trace status and body, distinguish forward from redirect, or spot an instance-field race. The POST trace above isolates validation and response construction; Java Servlets MCQs: 12 Solved Request Handling Questions adds practice on lifecycle, Servlet and JSP interfaces, response setup, dispatch, and shared state.

Claim

Correction

A new servlet is constructed for R1 and R2

Not required

doPost parses HTTP bytes before the container

The container creates request and response objects first

correct is already integer 18

getParameter returns "18"

finalScore=32 belongs in an instance field

Keep it local or appropriately scoped

Redirect preserves request attribute 32

It creates a new request

Headers can change after the JSON is committed

Configure them first

In a 45-second trace, mark the method and mapping, label each value by scope, and follow service() to the handler. Compute 18 x 2 = 36, 4 x 1 = 4, and 36 - 4 = 32. Fix the status before the body, then check for shared mutable state.

Short version and the next Java study step

Recall the chain: HTTP request -> container mapping -> request and response objects -> service() -> doPost() -> validate -> compute -> set status and headers -> write the body. Here 18 correct and 4 wrong produce 32; malformed or impossible values return 400. Redraw both diagrams and explain why R1 returns 32 while R2 returns 25. Continue with the Java Course: Concepts, MCQs & Coding Questions or the broader Complete Java Course.