Servlet Cookies and CGI Explained: State Management with a Worked Login Trace
Follow Asha's login from the first request to logout, then compare how a Java Servlet and a CGI program connect HTTP to trusted server-side session state.
KnowledgeGate Team
Exam prep & CS education

HTTP handles one request and response at a time, yet a login must be recognised on the next request. Learners mix up three jobs: a cookie carries a browser value, a server session holds trusted state, and Servlet or CGI defines how code receives a request and produces a response. Asha, user ID 42, signs in at 10:00:00 with three quiz attempts. The server issues s_7f3a, the browser returns it at 10:04:00, and logout at 10:08:00 invalidates both sides. Coding & Skills is the broader learning route for this topic.
Separate HTTP state from the server interface
The chain is browser -> HTTP request -> web server/container -> Servlet or CGI program -> session store -> HTTP response. HTTP does not remember Asha across requests. A cookie returns an identifier, while trusted values stay server-side. Servlet and CGI solve interfacing, not persistence by themselves.
Term | Lives where | Exact role in the worked trace |
|---|---|---|
Cookie | Browser cookie store | Carries |
Session record | Server store | Maps |
Servlet | Container-managed Java component | Reads |
CGI | Server/program interface | Supplies meta-variables and stdin, then accepts headers and body on stdout |
A persistent TCP connection is not an application session, and a cookie need not contain session data. Application Layer Protocols: DNS and HTTP Guide covers the HTTP foundation.

Read a cookie as a name-value pair plus scope rules
RFC 6265 defines it: a response sends Set-Cookie; the agent can return its name-value pair in Cookie on matches.
Set-Cookie: KGSESSION=s_7f3a; Max-Age=1800; Path=/portal; Secure; HttpOnly
Here KGSESSION is the name and s_7f3a the opaque value. 1800 / 60 = 30 minutes. /portal matches /portal/dashboard, /portal/profile, and /portal/cgi/dashboard, not /api/marks or /. No Domain means host-only. Secure requires secure transport; HttpOnly blocks non-HTTP API access. Path controls sending scope, not authorisation.
Logout deletes the record and overwrites the cookie at Path=/portal with an empty value and Max-Age=0. Browser-only deletion leaves a stolen ID usable. Store-only deletion leaves a stale cookie to reject.
Work the complete login, revisit and logout trace
Time | Request | Cookie before | Server action | Response | Cookie after |
|---|---|---|---|---|---|
09:59:50 |
| none | Lookup impossible |
| none |
10:00:00 |
| none | Validate fictitious credentials; create |
|
|
10:00:01 |
|
| Find Asha, attempts |
|
|
10:05:00 |
|
| Decrement |
|
|
10:08:00 |
|
| Delete record |
| none |
10:08:01 |
| none | No valid lookup |
| none |
10:31:00 | Replay | stale value | Lookup misses after deletion |
| unchanged |
Only the server changes 3 to 2. The cookie correlates; the store supplies identity and state.
String sid = requestCookie("KGSESSION");
Session data = sessionStore.find(sid);
if (data == null || data.isExpired()) rejectAndRedirect();
Session updated = sessionStore.decrementAttempts(sid); // quiz 7
writeQuizResponse(updated);Variables are local. Real applications need suitably generated unpredictable IDs. s_7f3a is teaching data.
A Servlet turns HTTP into Java request and response objects
Under Jakarta Servlet 6.1, the container maps POST /portal/login to LoginServlet, creates request and response objects, and service() dispatches to doPost(). It reads userId=42, asks services to create s_7f3a, then sets 303, Location: /portal/dashboard, and the traced Set-Cookie.
The container instantiates, calls init(), routes through service(), then calls destroy(). doGet() and doPost() are dispatch methods, not instances or service() replacements.
Users 42 and 77 may enter service() concurrently, so private String currentUser; can leak identity. Keep data local; use a concurrent session service. Do not assume any thread or instance count.
CGI exposes the same web exchange through environment and streams
Under RFC 3875, the server invokes CGI for POST /portal/cgi/login with REQUEST_METHOD=POST, SCRIPT_NAME=/portal/cgi/login, CONTENT_TYPE=application/x-www-form-urlencoded, and CONTENT_LENGTH=18. It reads 18 bytes from stdin: userId=42&pin=2468. This invented PIN must never be logged. This CGI branch starts from the same 10:00 login baseline as the Servlet branch, before the later quiz decrement.
Status: 303 See Other
Location: /portal/cgi/dashboard
Set-Cookie: KGSESSION=s_7f3a; Max-Age=1800; Path=/portal; Secure; HttpOnly
Content-Type: text/plain
RedirectingThe server interprets output; the script does not write a raw HTTP status line to the network. P202 gets REQUEST_METHOD=GET, SCRIPT_NAME=/portal/cgi/dashboard, and HTTP_COOKIE=KGSESSION=s_7f3a, with no body. It finds the record and outputs Status: 200 OK, Content-Type: text/plain, blank line, then Welcome Asha; attempts=3. Conventional CGI may start a process per request, so process memory is not the store.

Compare Servlet and CGI without mixing their responsibilities
Concern | Servlet | CGI |
|---|---|---|
Request input |
| Meta-variables plus stdin |
Response output |
| Headers and body on stdout |
Routing | Container URL mapping | Server configuration and |
Execution | Container-managed, possibly concurrent calls | Separate invocation in conventional CGI |
Cross-request state | Cookie plus | Cookie plus external store |
Main trap | Per-user instance fields | Assuming process memory survives |
Both read cookies, query SessionStore, and produce status, headers, body, and Set-Cookie. Cookies are not Servlet-only; CGI does not replace them. Correlation and invocation are independent. Container-managed Servlet calls and conventional CGI invocations differ in process model; no universal performance number follows from that distinction. Java Servlets: Server-Side Request Handling with a Worked HTTP Trace traces URL mapping, validation, and response construction in full. Cookie-backed session correlation and the CGI comparison are the separate concern in this login flow.
Repair the state, security and exam-trace traps
Mistake | Consequence | Correction |
|---|---|---|
Put | Client controls privilege | Keep role server-side |
Treat | URL match becomes access control | Authorise each request |
Omit | Insecure transport enters scope | Add |
Assume | CSRF and server flaws remain | Apply separate controls |
Store user in servlet field | Concurrent requests overwrite state | Use local data and session service |
Keep session in CGI memory | Next invocation cannot rely on it | Use external store |
Logout on one side | State may survive | Delete record and expire cookie |
Trust | Client input crosses boundary | Validate ID against live state |
A correct trace labels where state lives, applies cookie path rules, separates Servlet lifecycle from request dispatch, reads CGI variables and stdin, and rejects servlet fields or CGI process memory as per-user storage.
Try these before reading the answers:
Max-Age=1800in minutes?Which receives the cookie,
/portal/quiz/7or/api/marks?Where is
attempts=2?Which servlet method handles POST?
What carries the 18-byte CGI body?
What follows replay after logout?
Answers: (1) 30; (2) /portal/quiz/7; (3) server SessionStore; (4) doPost() through service(); (5) stdin with CONTENT_LENGTH=18; (6) lookup miss and redirect.
Short version and the next Java step
Retrieval chain: HTTP has no login memory; response sets s_7f3a; browser returns it on matches; server finds user 42 and attempts 3; Servlet or CGI adapts HTTP; logout clears both sides.
Set Path=/portal/quiz. It matches /portal/quiz/7 and /portal/quiz, not /portal/profile or /portal/quizzes under the boundary rule. Set expiry 10:05:00; at 10:06:00, reject the session even if the browser sends s_7f3a.
Redraw both diagrams, reproduce the seven rows, then build a request-local lookup without secrets in source or logs. Continue with Java: Concepts, MCQs & Coding Questions or Coding for Placements: C, C++, Java, Python.
Keep learning
Sessions and Cookies in Node.js: A Runnable Express Login Tutorial
Build the complete localhost flow, then trace what the browser sends, what Express stores, and why logout makes the dashboard anonymous again.
React State Management Options: Choose the Right Tool with Runnable Examples
Follow one cart and inventory example to decide where state belongs, trace each update, and choose the smallest React state tool that fits.
RNNs and LSTMs: Trace Hidden State Through a Three-Step Sequence
Follow one three-step input sequence through a vanilla RNN and an LSTM. The worked tables show every state update, gradient factor, gate branch, and common tracing trap.
Classes and Objects in C\u002b\u002b: Data Members, Methods and a Worked State Trace
Build a precise model of C++ classes and objects, then follow two WaterTank instances through valid, rejected, and independent state changes.





