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

Updated 25 Nov 20266 min read
Servlet Cookies and CGI Explained: State Management with a Worked Login Trace

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 KGSESSION=s_7f3a

Session record

Server store

Maps s_7f3a to user 42, Asha, student, attempts 3, expiry 10:30:00

Servlet

Container-managed Java component

Reads HttpServletRequest and fills HttpServletResponse

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.

Sequence diagram traces Asha’s session from login through dashboard access and logout, including session token s_7f3a, three attempts, and 10:30 expiry.

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

GET /portal/dashboard

none

Lookup impossible

302 /portal/login

none

10:00:00

POST /portal/login, user 42

none

Validate fictitious credentials; create s_7f3a

303 /portal/dashboard + Set-Cookie

s_7f3a

10:00:01

GET /portal/dashboard

s_7f3a

Find Asha, attempts 3

200

s_7f3a

10:05:00

GET /portal/quiz/7

s_7f3a

Decrement 3 - 1 = 2 in store

200 attempts=2

s_7f3a

10:08:00

POST /portal/logout

s_7f3a

Delete record

303 /portal/login, Max-Age=0

none

10:08:01

GET /portal/dashboard

none

No valid lookup

302 /portal/login

none

10:31:00

Replay Cookie: s_7f3a

stale value

Lookup misses after deletion

302 /portal/login

unchanged

Only the server changes 3 to 2. The cookie correlates; the store supplies identity and state.

java
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.

Code
Status: 303 See Other
Location: /portal/cgi/dashboard
Set-Cookie: KGSESSION=s_7f3a; Max-Age=1800; Path=/portal; Secure; HttpOnly
Content-Type: text/plain

Redirecting

The 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.

Split panel compares servlet and CGI login flows, showing Asha’s session s_7f3a, user ID 42, and CGI response headers with cookie data.

Compare Servlet and CGI without mixing their responsibilities

Concern

Servlet

CGI

Request input

HttpServletRequest

Meta-variables plus stdin

Response output

HttpServletResponse

Headers and body on stdout

Routing

Container URL mapping

Server configuration and SCRIPT_NAME

Execution

Container-managed, possibly concurrent calls

Separate invocation in conventional CGI

Cross-request state

Cookie plus HttpSession or external store

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 role=admin in a trusted-looking cookie

Client controls privilege

Keep role server-side

Treat Path as authorisation

URL match becomes access control

Authorise each request

Omit Secure on HTTPS cookie

Insecure transport enters scope

Add Secure

Assume HttpOnly stops every web attack

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 HTTP_COOKIE or parameters as identity

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:

  1. Max-Age=1800 in minutes?

  2. Which receives the cookie, /portal/quiz/7 or /api/marks?

  3. Where is attempts=2?

  4. Which servlet method handles POST?

  5. What carries the 18-byte CGI body?

  6. 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.