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

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.
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:
POST /practice/score?set=java-servlets HTTP/1.1
Host: example.test
Content-Type: application/x-www-form-urlencoded
correct=18&wrong=4&total=22Event | Observed value | Result |
|---|---|---|
Request method |
| Continue through HTTP dispatch |
Context path |
| Select the web application |
Servlet path |
| Match |
Query parameter |
| Available to the request, but not used in scoring |
Form parameters |
| Read as text |
Method dispatch |
| Select |
Parsing |
| Produce integers |
Validation |
| Accept the values |
Earned |
| Set |
Deduction |
| Set |
Final score |
| Set |
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}.

Keep parameters, attributes, scopes and concurrent requests separate
Value kind | Exact example | Lifetime or visibility | Use |
|---|---|---|---|
Request parameter |
| Client-supplied text for this request | Read input |
Local variable |
| This invocation only | Compute safely |
Request attribute |
| This request and a forward | Pass server-side data |
Session attribute |
| Requests in one session | Retain user-session state |
Servlet-context attribute |
| 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.

Error branches, response commitment, and forwarding
Invalid input and error branches
The code has deterministic error branches:
Missing
totalreturns400with{"error":"missing score field"}.correct=eighteen&wrong=4&total=22returns400with{"error":"score fields must be integers"}.correct=18&wrong=7&total=22fails because18 + 7 = 25 > 22, then returns400with{"error":"invalid score values"}.A GET reaches
doGet()and callssendError(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 |
| The container creates request and response objects first |
|
|
| Keep it local or appropriately scoped |
Redirect preserves request attribute | 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.
Keep learning
Java Servlets MCQs: 12 Solved Request Handling Questions
Solve 12 Java Servlet MCQs with teacher-led explanations, an exact request trace, lifecycle checks, JSP translation, and shared-state pitfalls.
Server-Side and Web Security: HTTP Sessions, Attacks, and Defences
Follow one illustrative login request from browser to proxy, application, and database, then map sessions, status codes, and common attacks to the controls that stop them.
Internet Fundamentals for GATE: DNS, HTTP and a Worked Web Request Trace
Connect Internet, Web, DNS, IP, ports and HTTP in one request lifecycle. Trace a cold HTTPS request and calculate latency, cache freshness and DNS expiry.
File Handling in C: Modes, Streams, a Worked File-Position Trace and Exam Traps
Learn how C streams, fopen modes, EOF checks and file positions work, then follow a five-byte trace that makes common output questions predictable.





