Java EE / Jakarta EE
Jakarta Servlet 6: Servlets, Filters, Sessions and the Web Tier
Beginner9 min readUpdated
Servlets are the lowest-level HTTP API in Jakarta EE and the foundation that Faces, Jakarta REST and Spring MVC are built on. This guide explains how the container maps requests to servlets, the life cycle and threading model, how to read requests and write responses, and how filters, listeners, sessions and asynchronous processing fit together, with examples that compile against Servlet 6.0.
What you will learn
- Explain the servlet life cycle and why a servlet must be thread-safe
- Map URLs to servlets and filters with annotations or web.xml
- Read parameters, headers, bodies and multipart uploads, and write responses with the correct encoding
- Use HttpSession and cookies correctly and know their security implications
- Apply filters, listeners and asynchronous processing to cross-cutting concerns
Every HTTP request that reaches a Jakarta EE application passes through the servlet container, whether the code that eventually handles it is a Faces page, a Jakarta REST resource, a Spring controller or a plain servlet. The Servlet specification defines how the container receives a request, chooses a component to handle it, exposes the request and response as Java objects, tracks sessions and lets you intercept the flow. You may rarely write a doGet method by hand in a modern project, but when a filter ordering bug, a character-encoding problem or a session fixation finding lands on your desk, this is the layer where the answer lives.
The container and the request cycle
A servlet container (Tomcat, Jetty, Undertow inside WildFly, the web engine inside Open Liberty and so on) listens on a port, parses HTTP, and for each request builds an HttpServletRequest and an HttpServletResponse. It then walks the deployed web applications to find the one whose context path matches (/shop for shop.war), picks the servlet whose URL pattern best matches the remaining path, runs the applicable filters, and finally calls the servlet's service method on a thread from its pool. When that method returns, the response is committed and the thread goes back to the pool.
URL patterns follow fixed matching rules, applied in this order: exact match (/orders/export), longest path prefix (/orders/*), extension (*.xhtml), and finally the default servlet (/). The default servlet serves static files from the WAR; the pattern /* is different from / and captures everything, including static resources, which is a classic misconfiguration.
Writing a servlet
A servlet is a class that extends jakarta.servlet.http.HttpServlet and overrides the methods for the HTTP methods it handles. Since Servlet 3.0 it is registered with an annotation; web.xml is optional.
package shop.web;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/orders/*", loadOnStartup = 1)
public class OrderServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String id = req.getPathInfo(); // "/42" for GET /shop/orders/42
if (id == null || id.length() < 2) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "order id required");
return;
}
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8"); // must precede getWriter()
resp.getWriter().printf("{\"id\":%s,\"status\":\"NEW\"}", id.substring(1));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String sku = req.getParameter("sku"); // form field or query parameter
int qty = Integer.parseInt(req.getParameter("qty"));
// ... create the order ...
resp.setStatus(HttpServletResponse.SC_CREATED);
resp.setHeader("Location", req.getContextPath() + "/orders/43");
}
}
The base class routes GET to doGet, POST to doPost and so on; the default implementation of each returns 405 Method Not Allowed, so unsupported methods are handled correctly without extra code. HEAD is derived from doGet automatically. OPTIONS and TRACE have defaults too — many teams disable TRACE at the server level for security reasons.
Life cycle and threading
The container instantiates the servlet once (at first request, or at startup when loadOnStartup is set), calls init(ServletConfig) once, then calls service for every request, possibly from dozens of threads at the same time, and finally calls destroy() when the application is undeployed. Three consequences follow:
- A servlet must not keep per-request state in fields. An instance field
private Order current;is a data race that shows up only under load. - Expensive, thread-safe resources (a
DataSource, a parsed template, an injected CDI bean) belong in fields initialised ininitor by injection. - Since Servlet 3.0, servlets in a CDI-enabled application are injection targets, so
@Inject OrderService service;works — but the servlet itself is not a CDI bean and has no CDI scope.
The old SingleThreadModel interface, which asked the container to serialise calls, was deprecated in Servlet 2.4 and finally removed in 6.0; it never solved the problem because sessions and context attributes were still shared.
Request and response in practice
HttpServletRequest gives you the method, the URI in pieces (getContextPath(), getServletPath(), getPathInfo(), getQueryString()), headers, cookies, parameters and the body. A few points that regularly cause bugs:
- Parameters merge the query string and a form-encoded body.
getParameterreturns the first value; usegetParameterValuesfor repeated names. CallinggetParameteron aPOSTreads and consumes the body, so you cannot afterwards read it as a stream. - Encoding of a form body defaults to ISO-8859-1 unless the request carries a charset, which browsers usually omit. Set the default once for the whole application rather than calling
setCharacterEncoding("UTF-8")in every servlet:
<!-- web.xml, Servlet 4.0+ -->
<request-character-encoding>UTF-8</request-character-encoding>
<response-character-encoding>UTF-8</response-character-encoding>
- Multipart uploads need
@MultipartConfigon the servlet (or the equivalent inweb.xml); thenreq.getPart("file")returns aPartwith a stream, size and submitted file name. SetmaxFileSizeandmaxRequestSizeto sensible limits — the defaults are unlimited. - Request attributes (
setAttribute/getAttribute) are the per-request scratch space, used to pass data from a filter or servlet to a forwarded JSP or Faces view.
On the response side, order matters: status, headers and content type must be set before the response is committed, which happens as soon as the buffer fills or you flush. After that, sendRedirect and setHeader are silently ignored or throw IllegalStateException. Redirects (sendRedirect) send a 302 back to the client with a new URL; forwards (req.getRequestDispatcher("/WEB-INF/views/order.jsp").forward(req, resp)) transfer control to another resource inside the server without the client knowing. Put views under WEB-INF so they cannot be requested directly.
Servlet 6.0 adds getRequestId(), getProtocolRequestId() (the HTTP/2 stream id) and getServletConnection(), which are useful for correlating log lines with the network layer.
Filters and listeners
A filter wraps the processing of matching requests. It runs before the servlet, can decide whether to continue the chain, and sees the response on the way out. Filters are the right tool for authentication checks, request logging, compression, CORS headers, security headers, and wrapping the request or response to change behaviour.
import java.io.IOException;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebFilter(urlPatterns = "/*")
public class SecurityHeadersFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
var resp = (HttpServletResponse) response;
resp.setHeader("X-Content-Type-Options", "nosniff");
resp.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
long start = System.nanoTime();
try {
chain.doFilter(request, response); // hand over to the next filter or the servlet
} finally {
var req = (HttpServletRequest) request;
System.out.printf("%s %s -> %d in %d ms%n", req.getMethod(), req.getRequestURI(),
resp.getStatus(), (System.nanoTime() - start) / 1_000_000);
}
}
}
Two details bite people. First, filters declared with annotations have no defined order; if order matters (authentication before logging, for instance) declare them in web.xml, where they run in declaration order, or use a single filter that delegates. Second, a filter is invoked for REQUEST dispatches only, by default; add dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD} if it must also see forwarded requests, and DispatcherType.ERROR for error-page rendering.
Listeners react to container events. ServletContextListener (@WebListener) runs code at application start and stop, the traditional place for one-off initialisation before CDI's @Observes @Initialized(ApplicationScoped.class) event existed. HttpSessionListener counts sessions or cleans up on expiry, and ServletRequestListener can set up per-request context such as a logging MDC.
Sessions and cookies
HTTP is stateless; HttpSession gives you server-side state keyed by an identifier the container sends to the browser, almost always as a cookie named JSESSIONID. req.getSession() creates a session if none exists; req.getSession(false) returns null instead, which is what you want in code that only reads. Attributes stored in the session must be Serializable if the server persists or replicates sessions across a cluster.
The security rules around sessions are well established and the servlet API supports all of them:
- Regenerate the id after login with
req.changeSessionId()(Servlet 3.1+) to defeat session fixation. - Mark the cookie
HttpOnlyandSecureso scripts cannot read it and it is never sent in clear text. Configure this inweb.xmlunder<session-config><cookie-config>or programmatically throughServletContext.getSessionCookieConfig(). - Set
SameSite. Servlet 6.0 finally addedCookie.setAttribute("SameSite", "Lax")and the matchingSessionCookieConfig.setAttribute, removing the need for server-specific settings. - Keep the timeout short and invalidate on logout with
session.invalidate(). - Keep sessions small. Session state is memory on the server and, in a cluster, network traffic on every change. Storing entity graphs or file contents in the session is the most common cause of memory pressure in web applications of this kind.
URL rewriting (;jsessionid=… appended to links) was the fallback for clients without cookies; Servlet 6.0 removed the isRequestedSessionIdFromUrl API and you should disable the mechanism with <tracking-mode>COOKIE</tracking-mode> because ids in URLs leak through logs and Referer headers.
Asynchronous processing
By default one container thread is tied up for the whole duration of a request. When the work is slow because it waits on something else — a remote call, a long database query, a message that has not arrived yet — that thread is wasted. Servlet 3.0 introduced AsyncContext so the request can be parked and completed later from another thread:
import java.io.IOException;
import jakarta.annotation.Resource;
import jakarta.enterprise.concurrent.ManagedExecutorService;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
@WebServlet(urlPatterns = "/report", asyncSupported = true)
public class ReportServlet extends HttpServlet {
@Resource // Jakarta Concurrency: a container-managed executor
ManagedExecutorService executor;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
AsyncContext ctx = req.startAsync();
ctx.setTimeout(30_000);
executor.submit(() -> {
String report = buildReport(); // slow work off the request thread
try {
ctx.getResponse().setContentType("text/plain;charset=UTF-8");
ctx.getResponse().getWriter().write(report);
} catch (IOException ignored) {
} finally {
ctx.complete(); // releases the request; forgetting this leaks it
}
});
}
}
Every filter in the chain must also declare asyncSupported = true, otherwise startAsync throws. Servlet 3.1 added non-blocking I/O (ReadListener/WriteListener) for streaming large bodies without blocking a thread; Jakarta REST's @Suspended AsyncResponse and Server-Sent Events are built on these facilities, so you normally use them through that API instead.
Error handling and security constraints
Uncaught exceptions and sendError calls are mapped to error pages declared in web.xml, matched by status code or exception type:
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/errors/not-found.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/WEB-INF/errors/failure.jsp</location>
</error-page>
Without these, the container renders its own page, which on some servers includes a stack trace — an information leak you should close before going live.
Declarative security also lives in web.xml: <security-constraint> elements bind URL patterns and HTTP methods to roles, and <login-config> selects an authentication method (FORM, BASIC, or a Jakarta Security authentication mechanism). A constraint with <auth-constraint/> and no roles denies everyone, and one with <user-data-constraint>CONFIDENTIAL</user-data-constraint> forces HTTPS. Programmatic checks use req.isUserInRole("admin"), req.getUserPrincipal() and, since Servlet 3.0, req.login, req.logout and req.authenticate. Note that constraints only cover the methods you list — or all methods if you list none — and omitting a method has historically allowed bypasses, so prefer listing none (protect everything) and using <http-method-omission> deliberately.
Pages, Expression Language and where views went
Jakarta Server Pages (JSP) and the Jakarta Standard Tag Library are still part of the platform and still work, but they are a legacy view technology: they compile to servlets, they mix markup and logic too easily, and Faces 4.0 no longer supports them as its view layer. The Expression Language (EL 5.0) that JSP popularised, on the other hand, is alive and used by Faces and by CDI's @Named beans. For new user interfaces you will typically choose between Jakarta Faces for server-rendered component UIs and a JavaScript front end talking to Jakarta REST endpoints; both of them, and Spring MVC, are ultimately servlets.
Common mistakes
- Instance fields holding request data. The symptom is one user occasionally seeing another user's data. Fix: local variables and request attributes only.
- Writing to the response before deciding the status. Once bytes are flushed you cannot redirect or change headers. Compute first, write last, and keep the response buffer large enough for small pages.
- Reading the body twice. After
getParameterorgetInputStreamthe body is gone. If a filter needs it, wrap the request in anHttpServletRequestWrapperthat caches the bytes. /*mapping on an application servlet. It swallows CSS, images and the Faces or REST servlet mappings. Use a prefix (/api/*) or exact paths.- Relying on annotation order for filters. Declare ordering-sensitive filters in
web.xml. - Session bloat and missing
HttpOnly/Secure/SameSite. These appear in every penetration-test report; configure the cookie once inweb.xml. - Forgetting
AsyncContext.complete(). The request hangs until the async timeout fires and the container logs a warning; the client sees a very slow error.
Key takeaways
- The servlet container parses HTTP, matches the URL to a servlet, runs the filter chain and calls
serviceon a pooled thread; Faces, Jakarta REST and Spring MVC all sit on top of this. - One servlet instance serves all requests concurrently, so keep state out of fields.
- Set status and headers before writing the body; use forward for internal dispatch and redirect when the client must see a new URL.
- Configure request and response encoding, session cookie flags, error pages and security constraints once in
web.xml; use annotations for the servlets, filters and listeners themselves. - Filters handle cross-cutting behaviour; declare them in
web.xmlwhen their order matters. - Asynchronous processing frees container threads during slow work, but every filter in the chain must support it and you must always call
complete(). - Servlet 6.0 removed legacy APIs, added
SameSitesupport through cookie attributes and added request and connection identifiers.
Sources and further reading
Frequently asked questions
- Is one servlet instance shared between all requests?
- Yes. The container creates a single instance per servlet declaration and calls its service method from many threads concurrently. Anything stored in an instance field is shared state; keep per-request data in local variables or request attributes and make any shared field immutable or properly synchronised.
- Do I still need web.xml?
- Not for declaring servlets, filters and listeners — annotations cover those since Servlet 3.0. web.xml is still the place for things annotations cannot express or that vary per environment: security constraints, error pages, session timeout, welcome files, default character encodings and ordering of filters declared in different libraries.
- What changed in Servlet 6.0 compared with 5.0?
- Servlet 6.0 removed APIs deprecated for years — SingleThreadModel, HttpSessionContext, HttpUtils and the URL-based session id methods — added Cookie.setAttribute for attributes such as SameSite, added request identifiers and connection information, and tightened URI handling so that ambiguous paths like encoded slashes are rejected by default.
- Should I write raw servlets or use a framework?
- For application code, use Jakarta REST for APIs and Faces or a front-end framework for user interfaces; both sit on the servlet API and handle routing, conversion and content negotiation for you. Write servlets and filters directly for infrastructure concerns such as authentication, logging, health endpoints and legacy integration.