HTTP middleware
suggest changeMost HTTP servers need the same things on every request: log it, attach a request ID, check credentials, add security headers, compress the response, turn exceptions into a clean 500. You don't want that code repeated in every handler. Middleware is code that wraps a handler. It runs before the handler, after it, or both, and it can decide not to call the handler at all.
Middleware is usually arranged in a chain. Each piece does its work and then passes the request to the next one. The last link is the actual handler:
request -> log -> request id -> auth -> handler
response <- log <- request id <- auth <- handler
Different Java stacks use different names for the same idea:
| Stack | Middleware API | Chain call |
|---|---|---|
JDK com.sun.net.httpserver |
Filter |
chain.doFilter(exchange) |
| Jakarta Servlet (Tomcat, Jetty, Undertow) | jakarta.servlet.Filter, HttpFilter |
chain.doFilter(req, resp) |
| Spring MVC | OncePerRequestFilter, HandlerInterceptor |
filterChain.doFilter(...) / preHandle returns true |
| Javalin, Helidon, Micronaut | before/after handlers, filters |
framework specific |
| Plain functions | UnaryOperator<HttpHandler> |
next.handle(exchange) |
Most of this article uses the JDK's built-in com.sun.net.httpserver.HttpServer, so the examples need no dependencies. The ideas carry over directly to servlet filters, which are shown at the end. Every example starts its own server on a free port (new InetSocketAddress("localhost", 0)) and calls it with java.net.http.HttpClient, so you can run it with java Example.java. All output below comes from JDK 25.
For headers in general see HTTP headers, and for building an API on top of HttpServer see REST APIs.
Filter and Filter.Chain
A com.sun.net.httpserver.Filter has one method to implement, doFilter(HttpExchange, Filter.Chain), plus description(). Filters are attached to an HttpContext, the object createContext() returns. Calling chain.doFilter(exchange) runs the next filter in the list. After the last filter it runs the context's handler.
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
public class FilterChain {
// A filter that prints a line before and after the rest of the chain
static class Trace extends Filter {
private final String name;
Trace(String name) { this.name = name; }
@Override
public void doFilter(HttpExchange ex, Chain chain) throws IOException {
System.out.println(name + ": before");
chain.doFilter(ex); // call the next filter, or the handler
System.out.println(name + ": after");
}
@Override
public String description() { return "trace " + name; }
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
HttpContext ctx = server.createContext("/hello", ex -> {
System.out.println("handler");
byte[] body = "hello\n".getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(200, body.length);
try (var out = ex.getResponseBody()) {
out.write(body);
}
});
ctx.getFilters().add(new Trace("outer"));
ctx.getFilters().add(new Trace("inner"));
server.start();
var client = HttpClient.newHttpClient();
var uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/hello");
var resp = client.send(HttpRequest.newBuilder(uri).build(),
HttpResponse.BodyHandlers.ofString());
System.out.print("client got " + resp.statusCode() + ": " + resp.body());
server.stop(0);
}
}
Output:
outer: before
inner: before
handler
inner: after
outer: after
client got 200: hello
Things to note:
getFilters()returns a mutableList<Filter>. Filters run in list order, so the first one added is the outermost.- Filters belong to a context, not to the server. If several contexts need the same filter, add it to each of them. Requests run concurrently, so keep per-request data out of filter fields. Then one instance can be shared by all contexts.
- Code after
chain.doFilter()runs after the handler returned. By then the response has usually been sent, so you can read the status code but you can't change headers. - A filter that doesn't call
chain.doFilter()stops the chain. It must then send a response itself.
Filter factory methods
For simple cases you don't need a subclass. Java 17 added Filter.beforeHandler and Filter.afterHandler, which wrap a Consumer<HttpExchange>. Java 18 added Filter.adaptRequest, which gives the rest of the chain a modified view of the request through the Request interface:
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class FilterFactories {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
var ctx = server.createContext("/", ex -> {
String text = "tenant=" + ex.getRequestHeaders().getFirst("X-Tenant") + "\n";
byte[] body = text.getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(200, body.length);
try (var out = ex.getResponseBody()) {
out.write(body);
}
});
var filters = ctx.getFilters();
// Java 17+: runs before the rest of the chain
filters.add(Filter.beforeHandler("server header",
ex -> ex.getResponseHeaders().set("Server", "demo")));
// Java 17+: runs after the handler returned (the response is already sent)
filters.add(Filter.afterHandler("log",
ex -> System.out.println("after: " + ex.getRequestURI() + " -> " + ex.getResponseCode())));
// Java 18+: the rest of the chain sees a modified view of the request
// Request.with() doesn't replace a header the client already sent
filters.add(Filter.adaptRequest("default tenant",
req -> req.with("X-Tenant", List.of("public"))));
server.start();
var client = HttpClient.newHttpClient();
var uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/a");
for (String tenant : new String[] {null, "acme"}) {
var b = HttpRequest.newBuilder(uri);
if (tenant != null) b.header("X-Tenant", tenant);
var resp = client.send(b.build(), HttpResponse.BodyHandlers.ofString());
System.out.print("client: Server=" + resp.headers().firstValue("Server").orElse("-")
+ " " + resp.body());
}
server.stop(0);
}
}
Output:
after: /a -> 200
client: Server=demo tenant=public
after: /a -> 200
client: Server=demo tenant=acme
beforeHandler is the right tool for adding response headers to every reply. afterHandler sees the final status code. Request.with(name, values) adds a header only if the request doesn't have it already, as the second request shows. It's good for defaults, not for overriding what the client sent.
Access logging and request IDs
An access log filter is the classic middleware: start a timer, run the chain, then log. Using finally makes sure a line is logged even if the handler throws. HttpExchange.getResponseCode() returns -1 if no response headers were sent.
Filters and handlers pass data to each other through attributes: setAttribute(name, value) and getAttribute(name) on the exchange. Here a request ID filter reuses the client's X-Request-Id or makes a new one, stores it as an attribute and echoes it in the response:
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
public class AccessLog {
// Logs method, path, status and duration of every request
static class LogFilter extends Filter {
@Override
public void doFilter(HttpExchange ex, Chain chain) throws IOException {
long start = System.nanoTime();
try {
chain.doFilter(ex);
} finally {
long ms = (System.nanoTime() - start) / 1_000_000;
// getResponseCode() is -1 if the handler never sent headers
System.out.printf("%s %s %s -> %d (%d ms) id=%s%n",
ex.getRemoteAddress().getAddress().getHostAddress(),
ex.getRequestMethod(), ex.getRequestURI(),
ex.getResponseCode(), ms, ex.getAttribute("requestId"));
}
}
@Override
public String description() { return "access log"; }
}
static final AtomicInteger nextId = new AtomicInteger(1);
// Filter.beforeHandler (Java 17+) wraps a Consumer<HttpExchange> that runs before the chain
static final Filter requestId = Filter.beforeHandler("request id", ex -> {
String id = ex.getRequestHeaders().getFirst("X-Request-Id");
if (id == null) {
id = "req-" + nextId.getAndIncrement();
}
ex.setAttribute("requestId", id); // visible to later filters and the handler
ex.getResponseHeaders().set("X-Request-Id", id);
});
static void send(HttpExchange ex, int status, String text) throws IOException {
byte[] body = text.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
ex.sendResponseHeaders(status, body.length);
try (var out = ex.getResponseBody()) {
out.write(body);
}
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
var ctx = server.createContext("/", ex -> {
if (!ex.getRequestURI().getPath().equals("/")) {
send(ex, 404, "not found\n");
return;
}
send(ex, 200, "home, request " + ex.getAttribute("requestId") + "\n");
});
// the request id filter runs first, so the id is in place for logging
ctx.getFilters().add(requestId);
ctx.getFilters().add(new LogFilter());
server.start();
var client = HttpClient.newHttpClient();
String base = "http://localhost:" + server.getAddress().getPort();
for (var req : new HttpRequest[] {
HttpRequest.newBuilder(URI.create(base + "/")).build(),
HttpRequest.newBuilder(URI.create(base + "/missing")).build(),
HttpRequest.newBuilder(URI.create(base + "/"))
.header("X-Request-Id", "abc-123").build() }) {
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.print("client: " + resp.statusCode() + " "
+ resp.headers().firstValue("X-Request-Id").orElse("-") + " " + resp.body());
}
server.stop(0);
}
}
Output:
127.0.0.1 GET / -> 200 (38 ms) id=req-1
client: 200 req-1 home, request req-1
127.0.0.1 GET /missing -> 404 (0 ms) id=req-2
client: 404 req-2 not found
127.0.0.1 GET / -> 200 (0 ms) id=abc-123
client: 200 abc-123 home, request abc-123
The first request is slow because the JVM is still loading and compiling classes.
Exchange attributes are per request. Don't confuse them with HttpContext.getAttributes(), a map shared by every request to that context. Use it for configuration, not for request data.
In production you would write to a System.Logger or SLF4J logger instead of System.out. Put the request ID into the logging context (for example SLF4J's MDC) so every log line written while handling the request includes it.
Short-circuiting: authentication
A filter that rejects a request sends its own response and returns without calling chain.doFilter(). The handler never runs. This is how authentication, rate limiting and request size checks work.
The example has an authentication filter that looks up a bearer token and stores the user as an attribute. A second filter, used only on /admin, depends on that attribute to check the user's role. /public has no filters.
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class AuthFilter {
record User(String name, String role) {}
// Checks "Authorization: Bearer <token>". On failure it answers 401 and
// does NOT call chain.doFilter(), so the handler never runs.
static class BearerAuth extends Filter {
private final Map<String, User> tokens;
BearerAuth(Map<String, User> tokens) { this.tokens = tokens; }
@Override
public void doFilter(HttpExchange ex, Chain chain) throws IOException {
String auth = ex.getRequestHeaders().getFirst("Authorization");
User user = null;
if (auth != null && auth.regionMatches(true, 0, "Bearer ", 0, 7)) {
user = tokens.get(auth.substring(7).strip());
}
if (user == null) {
ex.getResponseHeaders().set("WWW-Authenticate", "Bearer");
send(ex, 401, "unauthorized\n");
return; // short-circuit
}
ex.setAttribute("user", user);
chain.doFilter(ex);
}
@Override
public String description() { return "bearer auth"; }
}
// A second filter that relies on the attribute set by the first
static Filter requireRole(String role) {
return new Filter() {
@Override
public void doFilter(HttpExchange ex, Chain chain) throws IOException {
User user = (User) ex.getAttribute("user");
if (!user.role().equals(role)) {
send(ex, 403, "forbidden\n");
return;
}
chain.doFilter(ex);
}
@Override
public String description() { return "require role " + role; }
};
}
static void send(HttpExchange ex, int status, String text) throws IOException {
byte[] body = text.getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(status, body.length);
try (var out = ex.getResponseBody()) {
out.write(body);
}
}
public static void main(String[] args) throws Exception {
var tokens = Map.of(
"t-alice", new User("alice", "admin"),
"t-bob", new User("bob", "user"));
var auth = new BearerAuth(tokens);
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/public", ex -> send(ex, 200, "anyone can see this\n"));
HttpHandler me = ex -> send(ex, 200, "hello " + ((User) ex.getAttribute("user")).name() + "\n");
server.createContext("/me", me).getFilters().add(auth);
var admin = server.createContext("/admin", ex -> send(ex, 200, "admin area\n"));
admin.getFilters().add(auth);
admin.getFilters().add(requireRole("admin"));
server.start();
var client = HttpClient.newHttpClient();
String base = "http://localhost:" + server.getAddress().getPort();
String[][] calls = {
{"/public", null}, {"/me", null}, {"/me", "wrong"},
{"/me", "t-bob"}, {"/admin", "t-bob"}, {"/admin", "t-alice"} };
for (String[] c : calls) {
var b = HttpRequest.newBuilder(URI.create(base + c[0]));
if (c[1] != null) b.header("Authorization", "Bearer " + c[1]);
var resp = client.send(b.build(), HttpResponse.BodyHandlers.ofString());
System.out.printf("%-8s %-8s %d %s", c[0], c[1], resp.statusCode(), resp.body());
}
server.stop(0);
}
}
Output:
/public null 200 anyone can see this
/me null 401 unauthorized
/me wrong 401 unauthorized
/me t-bob 200 hello bob
/admin t-bob 403 forbidden
/admin t-alice 200 admin area
401 Unauthorized means "I don't know who you are" and should come with a WWW-Authenticate header. 403 Forbidden means "I know who you are and you're not allowed". The order of filters matters here: requireRole assumes the user attribute is set, so it must come after BearerAuth.
For HTTP Basic authentication the JDK has a ready-made filter: subclass com.sun.net.httpserver.BasicAuthenticator, implement checkCredentials(user, password) and install it with ctx.setAuthenticator(...). The handler then gets the user from exchange.getPrincipal(). For session cookies see Sessions.
Recovering from exceptions
If a handler throws, HttpServer doesn't send a 500. It just closes the connection, and the client gets a confusing I/O error. A recover filter catches the exception and sends a proper error response, but only if the handler hadn't already sent headers:
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
public class Recover {
// Turns an exception thrown by a handler into a 500 response
static class RecoverFilter extends Filter {
@Override
public void doFilter(HttpExchange ex, Chain chain) throws IOException {
try {
chain.doFilter(ex);
} catch (Exception e) {
System.out.println("handler failed: " + e);
if (ex.getResponseCode() == -1) { // headers not sent yet
byte[] body = "internal server error\n".getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(500, body.length);
ex.getResponseBody().write(body);
}
ex.close();
}
}
@Override
public String description() { return "recover"; }
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/raw", ex -> { throw new IllegalStateException("boom"); });
server.createContext("/safe", ex -> { throw new IllegalStateException("boom"); })
.getFilters().add(new RecoverFilter());
server.start();
var client = HttpClient.newHttpClient();
String base = "http://localhost:" + server.getAddress().getPort();
for (String path : new String[] {"/raw", "/safe"}) {
try {
var resp = client.send(HttpRequest.newBuilder(URI.create(base + path)).build(),
HttpResponse.BodyHandlers.ofString());
System.out.print(path + ": " + resp.statusCode() + " " + resp.body());
} catch (IOException e) {
System.out.println(path + ": " + e);
}
}
server.stop(0);
}
}
Output:
/raw: java.io.IOException: HTTP/1.1 header parser received no bytes
handler failed: java.lang.IllegalStateException: boom
/safe: 500 internal server error
Put the recover filter first (outermost), so it also catches exceptions from the other filters. Never put the exception message or stack trace in the response body. It can reveal internal details to an attacker. Log it on the server instead.
Middleware as handler wrappers
You don't have to use Filter at all. A middleware can be a function that takes an HttpHandler and returns a new HttpHandler that wraps it. This is the style used by Go's net/http and many Node.js frameworks. Since a lambda can implement HttpHandler, each middleware is a few lines. Java 18 also added HttpHandlers with building blocks: HttpHandlers.of(status, headers, body) returns a fixed response, and HttpHandlers.handleOrElse(predicate, handler, fallback) picks one of two handlers.
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpHandlers;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.function.UnaryOperator;
public class Middleware {
// A middleware takes a handler and returns a new handler that wraps it
interface Mw extends UnaryOperator<HttpHandler> {}
// chain(h, a, b, c) == a(b(c(h))): the first middleware is the outermost
static HttpHandler chain(HttpHandler h, Mw... mws) {
for (int i = mws.length - 1; i >= 0; i--) {
h = mws[i].apply(h);
}
return h;
}
static Mw logging(String tag) {
return next -> ex -> {
try {
next.handle(ex);
} finally {
System.out.printf("[%s] %s %s -> %d%n", tag, ex.getRequestMethod(),
ex.getRequestURI().getPath(), ex.getResponseCode());
}
};
}
static Mw recover() {
return next -> ex -> {
try {
next.handle(ex);
} catch (RuntimeException e) {
if (ex.getResponseCode() == -1) {
ex.sendResponseHeaders(500, -1); // -1 means: no body
}
ex.close();
}
};
}
// HttpHandlers (Java 18+) has ready-made building blocks
static Mw allowMethods(String... methods) {
Set<String> allowed = Set.of(methods);
HttpHandler notAllowed = HttpHandlers.of(405,
Headers.of("Allow", String.join(", ", methods)), "");
return next -> HttpHandlers.handleOrElse(
req -> allowed.contains(req.getRequestMethod()), next, notAllowed);
}
static void text(HttpExchange ex, String s) throws IOException {
byte[] body = s.getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(200, body.length);
try (var out = ex.getResponseBody()) {
out.write(body);
}
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/time", chain(ex -> text(ex, "12:00\n"),
logging("app"), recover(), allowMethods("GET", "HEAD")));
server.createContext("/crash", chain(ex -> {
throw new IllegalStateException("bug");
}, logging("app"), recover()));
server.start();
var client = HttpClient.newHttpClient();
String base = "http://localhost:" + server.getAddress().getPort();
String[][] calls = { {"GET", "/time"}, {"DELETE", "/time"}, {"GET", "/crash"} };
for (String[] c : calls) {
var req = HttpRequest.newBuilder(URI.create(base + c[1]))
.method(c[0], HttpRequest.BodyPublishers.noBody()).build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.printf("client: %s %s -> %d %s allow=%s%n", c[0], c[1], resp.statusCode(),
resp.body().strip(), resp.headers().firstValue("Allow").orElse("-"));
}
server.stop(0);
}
}
Output:
[app] GET /time -> 200
client: GET /time -> 200 12:00 allow=-
[app] DELETE /time -> 405
client: DELETE /time -> 405 allow=GET, HEAD
[app] GET /crash -> 500
client: GET /crash -> 500 allow=-
chain() applies the middleware from the last to the first, so the first one in the argument list ends up outermost. That makes the list read in the order the request passes through it, just like getFilters().
Filter or handler wrappers? They do the same job. Wrappers are plain functions, easy to test without a server, and can be composed into a ready-made stack and reused. Filters show up in HttpContext.getFilters() and can be added or removed after the context was created. Pick one style per project and stick to it.
Changing the response: gzip compression
Some middleware needs to change what the handler writes, not just look at it. Compression, response caching and body rewriting all work this way. With HttpServer you do it by passing a wrapped exchange down the chain. HttpExchange is an abstract class, so a wrapper that forwards every method to the real exchange can then override just what it changes.
The gzip wrapper overrides sendResponseHeaders() to add Content-Encoding: gzip and switch to chunked encoding, since the compressed size isn't known in advance. It also overrides getResponseBody() to return a GZIPOutputStream. The handler doesn't know it's being compressed:
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpPrincipal;
import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GzipFilter {
// Forwards everything to the real exchange. Subclasses override what they change.
static class ExchangeWrapper extends HttpExchange {
protected final HttpExchange ex;
ExchangeWrapper(HttpExchange ex) { this.ex = ex; }
public Headers getRequestHeaders() { return ex.getRequestHeaders(); }
public Headers getResponseHeaders() { return ex.getResponseHeaders(); }
public URI getRequestURI() { return ex.getRequestURI(); }
public String getRequestMethod() { return ex.getRequestMethod(); }
public HttpContext getHttpContext() { return ex.getHttpContext(); }
public void close() { ex.close(); }
public InputStream getRequestBody() { return ex.getRequestBody(); }
public OutputStream getResponseBody() { return ex.getResponseBody(); }
public void sendResponseHeaders(int code, long len) throws IOException {
ex.sendResponseHeaders(code, len);
}
public InetSocketAddress getRemoteAddress() { return ex.getRemoteAddress(); }
public int getResponseCode() { return ex.getResponseCode(); }
public InetSocketAddress getLocalAddress() { return ex.getLocalAddress(); }
public String getProtocol() { return ex.getProtocol(); }
public Object getAttribute(String name) { return ex.getAttribute(name); }
public void setAttribute(String name, Object v) { ex.setAttribute(name, v); }
public void setStreams(InputStream i, OutputStream o) { ex.setStreams(i, o); }
public HttpPrincipal getPrincipal() { return ex.getPrincipal(); }
}
static class GzipExchange extends ExchangeWrapper {
private GZIPOutputStream gzip;
GzipExchange(HttpExchange ex) { super(ex); }
@Override
public void sendResponseHeaders(int code, long len) throws IOException {
if (len == -1) { // no body: nothing to compress
ex.sendResponseHeaders(code, len);
return;
}
ex.getResponseHeaders().set("Content-Encoding", "gzip");
ex.getResponseHeaders().add("Vary", "Accept-Encoding");
ex.sendResponseHeaders(code, 0); // 0 = chunked: compressed size is unknown
gzip = new GZIPOutputStream(ex.getResponseBody());
}
@Override
public OutputStream getResponseBody() {
return gzip != null ? gzip : ex.getResponseBody();
}
@Override
public void close() {
try {
if (gzip != null) gzip.close(); // writes the gzip trailer
} catch (IOException ignored) {
}
ex.close();
}
}
static class Gzip extends Filter {
@Override
public void doFilter(HttpExchange ex, Chain chain) throws IOException {
String ae = ex.getRequestHeaders().getFirst("Accept-Encoding");
if (ae != null && ae.contains("gzip")) {
chain.doFilter(new GzipExchange(ex)); // later filters and the handler see the wrapper
} else {
chain.doFilter(ex);
}
}
@Override
public String description() { return "gzip"; }
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
// The handler knows nothing about compression
server.createContext("/data", ex -> {
byte[] body = "hello gzip! ".repeat(100).getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
ex.sendResponseHeaders(200, body.length);
try (OutputStream out = ex.getResponseBody()) {
out.write(body);
}
}).getFilters().add(new Gzip());
server.start();
// HttpClient doesn't decompress automatically, so we ask for gzip ourselves
var client = HttpClient.newHttpClient();
var uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/data");
for (String enc : new String[] {"identity", "gzip"}) {
var req = HttpRequest.newBuilder(uri).header("Accept-Encoding", enc).build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofByteArray());
byte[] raw = resp.body();
String encoding = resp.headers().firstValue("Content-Encoding").orElse("none");
byte[] decoded = encoding.equals("gzip")
? new GZIPInputStream(new ByteArrayInputStream(raw)).readAllBytes()
: raw;
System.out.printf("Accept-Encoding: %-8s -> Content-Encoding: %-4s %4d bytes on the wire, %d decoded%n",
enc, encoding, raw.length, decoded.length);
}
server.stop(0);
}
}
Output:
Accept-Encoding: identity -> Content-Encoding: none 1200 bytes on the wire, 1200 decoded
Accept-Encoding: gzip -> Content-Encoding: gzip 43 bytes on the wire, 1200 decoded
Details that matter:
sendResponseHeaders(code, 0)means chunked transfer encoding,-1means no body, and a positive number is the exact body length. The wrapper must replace the handler's length, because the handler's length is the uncompressed size.Vary: Accept-Encodingtells caches that the response depends on that request header.- Closing the response body stream completes the exchange.
GZIPOutputStream.close()writes the gzip trailer and then closes the underlying stream, so a handler that uses try-with-resources works unchanged. - The
contains("gzip")check is simplified. A full implementation parsesAccept-Encoding, honoursgzip;q=0, and skips small or already compressed bodies such as images. java.net.http.HttpClientdoesn't decompress automatically. That's why the client asks for gzip explicitly and decodes it withGZIPInputStream.
Servlet filters
In a servlet container (Tomcat, Jetty, Undertow, or Spring Boot, which runs on one of them) middleware is a jakarta.servlet.Filter. Extending jakarta.servlet.http.HttpFilter gives you typed HttpServletRequest and HttpServletResponse objects. The shape is the same as before: do work, call chain.doFilter(req, resp) or send an error and return.
This example runs an embedded Jetty 12.1 server. Put these jars in lib and run it with java -cp "lib/*" ServletFilters.java:
lib/jetty-server-12.1.14.jar
lib/jetty-http-12.1.14.jar
lib/jetty-io-12.1.14.jar
lib/jetty-util-12.1.14.jar
lib/jetty-security-12.1.14.jar
lib/jetty-session-12.1.14.jar
lib/jetty-ee10-servlet-12.1.14.jar
lib/jakarta.servlet-api-6.0.0.jar
lib/slf4j-api-2.0.17.jar
lib/slf4j-nop-2.0.17.jar
With Maven or Gradle a single dependency is enough: org.eclipse.jetty.ee10:jetty-ee10-servlet:12.1.14.
import jakarta.servlet.DispatcherType;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.EnumSet;
import org.eclipse.jetty.ee10.servlet.FilterHolder;
import org.eclipse.jetty.ee10.servlet.ServletContextHandler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
public class ServletFilters {
// HttpFilter (Servlet 4.0+) gives typed request/response objects
public static class LogFilter extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
throws IOException, ServletException {
try {
chain.doFilter(req, resp);
} finally {
System.out.printf("log: %s %s -> %d%n",
req.getMethod(), req.getRequestURI(), resp.getStatus());
}
}
}
public static class ApiKeyFilter extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
throws IOException, ServletException {
if (!"secret".equals(req.getHeader("X-Api-Key"))) {
resp.sendError(401, "missing or bad API key");
return; // short-circuit
}
req.setAttribute("client", "key-owner"); // like HttpExchange.setAttribute
chain.doFilter(req, resp);
}
}
public static class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("hello " + req.getAttribute("client"));
}
}
public static void main(String[] args) throws Exception {
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setHost("localhost");
connector.setPort(0); // any free port
server.addConnector(connector);
var ctx = new ServletContextHandler();
ctx.addServlet(HelloServlet.class, "/api/*");
ctx.addServlet(HelloServlet.class, "/");
// filters run in the order they are added (like <filter-mapping> order in web.xml)
var requests = EnumSet.of(DispatcherType.REQUEST);
ctx.addFilter(new FilterHolder(new LogFilter()), "/*", requests);
ctx.addFilter(new FilterHolder(new ApiKeyFilter()), "/api/*", requests);
server.setHandler(ctx);
server.start();
var client = HttpClient.newHttpClient();
String base = "http://localhost:" + connector.getLocalPort();
String[][] calls = { {"/", null}, {"/api/x", null}, {"/api/x", "secret"} };
for (String[] c : calls) {
var b = HttpRequest.newBuilder(URI.create(base + c[0]));
if (c[1] != null) b.header("X-Api-Key", c[1]);
var resp = client.send(b.build(), HttpResponse.BodyHandlers.ofString());
String body = resp.statusCode() == 200 ? resp.body().strip() : "(error page)";
System.out.printf("client: %-7s key=%-6s -> %d %s%n", c[0], c[1], resp.statusCode(), body);
}
server.stop();
}
}
Output:
log: GET / -> 200
client: / key=null -> 200 hello null
log: GET /api/x -> 401
client: /api/x key=null -> 401 (error page)
log: GET /api/x -> 200
client: /api/x key=secret -> 200 hello key-owner
Differences from HttpServer filters:
- Filters are mapped to URL patterns (
/*,/api/*), not attached to a handler, so one filter can cover the whole app. - Request attributes (
req.setAttribute) play the role of exchange attributes. resp.sendError(401, msg)lets the container render the error page.resp.getStatus()works at any time.- To change the response body, wrap the response in an
HttpServletResponseWrapperand pass the wrapper tochain.doFilter(). It's the same idea as the gzip exchange wrapper above. - In a WAR, filters are registered with
@WebFilter("/api/*")or inweb.xml. In Spring Boot, aFilterbean is registered automatically. Extend Spring'sOncePerRequestFilterso the filter doesn't run twice when a request is forwarded or dispatched to an error page.
Spring MVC also has HandlerInterceptor, which runs inside the DispatcherServlet after the controller method was chosen. Use an interceptor when you need to know which controller handles the request. Use a filter for everything that's about raw HTTP: logging, compression, CORS, security headers. Spring Security itself is a chain of servlet filters.
Ordering middleware
The order of the chain is part of its behavior. A typical order, from outermost to innermost:
| Position | Middleware | Why there |
|---|---|---|
| 1 | Recover from exceptions | Catches failures in everything below it |
| 2 | Request ID | Later middleware and log lines can use the ID |
| 3 | Access log | Sees the final status, including rejected requests |
| 4 | Security headers, CORS | Must apply to error responses too |
| 5 | Compression | Wraps the body that the inner layers write |
| 6 | Authentication | Rejects anonymous requests early |
| 7 | Authorization | Needs the user set by authentication |
| 8 | Handler |
If authentication ran before logging, rejected requests would never be logged. If it ran before CORS, a browser's preflight OPTIONS request, which carries no credentials, would be rejected with 401.
Summary
- Middleware wraps a handler to run code before and after it, or instead of it. The chain runs in order, and the first entry is the outermost.
- With the JDK's
HttpServer, extendFilter, callchain.doFilter(exchange)to continue, and add the filter withcontext.getFilters().add(...). For simple cases useFilter.beforeHandler,Filter.afterHandlerandFilter.adaptRequest. - To stop a request, send a response and return without calling
chain.doFilter(). - Pass per-request data with
exchange.setAttribute(). Code afterchain.doFilter()can readgetResponseCode()but can't change headers that were already sent. - Wrap handler exceptions in a recover filter, because
HttpServerjust drops the connection. - To change the response, pass a wrapped
HttpExchange(orHttpServletResponseWrapperin servlets) down the chain. - Middleware can also be plain
UnaryOperator<HttpHandler>functions, which are easy to compose and test. - Servlet filters (
HttpFilter, Spring'sOncePerRequestFilter) work the same way and are mapped to URL patterns.