Routing by method and path by hand
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite must show one product at GET /api/v1/products/42 and remove it with DELETE. The JDK server only matches the start of a path, so a mistyped address must become a clear 404 in your own code.
Contexts match by prefix: what /api/v1/products really receives
A context is a path connected to a handler, and it matches by text prefix: /api/v1/products also receives /api/v1/products/42 and /api/v1/productsXYZ. The longest matching context wins, and / catches the rest.
Example 1 registers three contexts and shows which one catches each path.
Example 1 · Which context gets which path
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;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;
public class ContextPrefixDemo {
/** Answers with the context that caught the request, so we can see who got what. */ static void whoAmI(HttpExchange exchange) throws IOException { byte[] body = ("context " + exchange.getHttpContext().getPath()).getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(200, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/", ContextPrefixDemo::whoAmI); server.createContext("/api/v1/products", ContextPrefixDemo::whoAmI); server.createContext("/api/v1/products/export", ContextPrefixDemo::whoAmI); server.start();
String base = "http://127.0.0.1:" + server.getAddress().getPort(); HttpClient client = HttpClient.newHttpClient(); String[] paths = {"/api/v1/products", "/api/v1/products/42", "/api/v1/products/42/reviews", "/api/v1/products/export", "/api/v1/productsXYZ", "/api/v1/categories", "/favicon.ico"}; try { for (String path : paths) { HttpResponse<String> r = client.send(HttpRequest.newBuilder(URI.create(base + path)).build(), HttpResponse.BodyHandlers.ofString()); System.out.printf("%-28s -> %s%n", path, r.body()); } } finally { server.stop(0); } }}/api/v1/products -> context /api/v1/products /api/v1/products/42 -> context /api/v1/products /api/v1/products/42/reviews -> context /api/v1/products /api/v1/products/export -> context /api/v1/products/export /api/v1/productsXYZ -> context /api/v1/products /api/v1/categories -> context / /favicon.ico -> context /
What this code does
- Three contexts:
/,/api/v1/productsand/api/v1/products/export. Each handler answers with the context that caught the request. /api/v1/products/42/reviewsand even/api/v1/productsXYZgo to/api/v1/products, because matching is a plain text prefix./api/v1/products/exportgoes to the longer context, and everything else falls to/.
A handler that does not check the full path answers addresses that do not exist: /api/v1/productsXYZ would return the product list with 200, and a typo in a client becomes a silent wrong answer instead of a clear 404.
The usual design is one context for / with one handler, the router, that looks at the full path and the method of every request.
Predict the output
Which context answers?
Three contexts exist: /, /api/v1/products and /api/v1/products/export.
Round 1 of 3
Which handler answers GET /api/v1/products/42?
exchange.getHttpContext().getPath() tells you which context caught the request. It is useful when you debug routing.Reading the method, path and query string
Raw query is the part of the URL after ?, exactly as it arrived and still encoded, such as q=cover%26case&page=0. getRawQuery() returns it; split it on & and =, then decode each name and value.
Example 2 reads the method, path and query of one request and builds a parameter map.
Example 2 · Method, path, raw query and a decoded parameter map
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.URLDecoder;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class RequestPartsDemo {
/** Splits the RAW query on & and =, then decodes each name and value. */ static Map<String, List<String>> parseQuery(String rawQuery) { Map<String, List<String>> params = new LinkedHashMap<>(); if (rawQuery == null) { return params; // no ? in the URL } for (String pair : rawQuery.split("&")) { String[] parts = pair.split("=", 2); String name = URLDecoder.decode(parts[0], StandardCharsets.UTF_8); String value = parts.length > 1 ? URLDecoder.decode(parts[1], StandardCharsets.UTF_8) : ""; params.computeIfAbsent(name, key -> new ArrayList<>()).add(value); } return params; }
static void echo(HttpExchange exchange) throws IOException { URI uri = exchange.getRequestURI(); System.out.println("method: " + exchange.getRequestMethod()); System.out.println("path: " + uri.getPath()); System.out.println("rawQuery: " + uri.getRawQuery()); System.out.println("query: " + uri.getQuery() + " <- decoded first: the & inside q is lost"); System.out.println("params: " + parseQuery(uri.getRawQuery())); exchange.sendResponseHeaders(204, -1); exchange.close(); }
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/products", RequestPartsDemo::echo); server.start();
String url = "http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/products?q=cover%26case&categoryId=4&sort=price,desc&status=NEW&status=SALE"; try { HttpClient.newHttpClient().send(HttpRequest.newBuilder(URI.create(url)).build(), HttpResponse.BodyHandlers.discarding()); } finally { server.stop(0); } }}method: GET
path: /api/v1/products
rawQuery: q=cover%26case&categoryId=4&sort=price,desc&status=NEW&status=SALE
query: q=cover&case&categoryId=4&sort=price,desc&status=NEW&status=SALE <- decoded first: the & inside q is lost
params: {q=[cover&case], categoryId=[4], sort=[price,desc], status=[NEW, SALE]}What this code does
- The client searches for
cover&case, so the&is sent encoded as%26.getRawQuery()keeps it encoded;getQuery()decodes it, and the value can no longer be told apart from the next parameter. parseQuerysplits the raw text first and decodes each part after, soqkeepscover&caseand the repeatedstatuskeeps both values in a list.
exchange.getRequestMethod() returns the method in capitals, such as GET. exchange.getRequestURI() returns the URI after the host: getPath() gives the decoded path and getRawQuery() the query string as it arrived.
Split the raw query first and decode each part after, with URLDecoder.decode(text, UTF_8). Do not use getQuery(): it decodes first, so an encoded & inside a value (%26) turns into a real & and splits the value in two. A name can appear more than once (status=NEW&status=SALE), so a Map<String, List<String>> keeps every value.
Path variables: /products/42 parsed safely
A path variable is the changing part of a path, such as 42 in /api/v1/products/42. The client controls it, so treat it as untrusted text: it may be abc, -5, 007, 99999999999 or 42/reviews.
Example 3 reads the id with Integer.parseInt and fails. Example 4 fixes it with a pattern that must match the whole path.
Example 3 · Mistake: Integer.parseInt on the path
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;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;
public class UnsafeIdDemo {
static void product(HttpExchange exchange) throws IOException { String path = exchange.getRequestURI().getPath(); int id = Integer.parseInt(path.substring("/api/v1/products/".length())); // trusts the client byte[] body = ("product " + id).getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(200, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/products/", UnsafeIdDemo::product); server.start();
String base = "http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/products/"; HttpClient client = HttpClient.newHttpClient(); try { for (String id : new String[] {"42", "abc", "42/reviews", "99999999999"}) { try { HttpResponse<String> r = client.send(HttpRequest.newBuilder(URI.create(base + id)).build(), HttpResponse.BodyHandlers.ofString()); System.out.println(id + " -> " + r.statusCode() + " " + r.body()); } catch (IOException e) { System.out.println(id + " -> " + e.getClass().getSimpleName() + ": " + e.getMessage()); } } } finally { server.stop(0); } }}42 -> 200 product 42 abc -> IOException: HTTP/1.1 header parser received no bytes 42/reviews -> IOException: HTTP/1.1 header parser received no bytes 99999999999 -> IOException: HTTP/1.1 header parser received no bytes
What this code does
42works. Forabc,42/reviewsand99999999999(too big forint),parseIntthrowsNumberFormatExceptioninside the handler.- The JDK swallows that exception and closes the connection with no response, so the client only sees
header parser received no bytes, and the server console shows nothing at all.
Example 4 · The fix: a pattern that must match the whole path
import java.util.OptionalInt;import java.util.regex.Matcher;import java.util.regex.Pattern;
public class PathIdDemo {
/** /api/v1/products/{id}: a positive whole number, no sign, no leading zero, at most 9 digits. */ private static final Pattern PRODUCT = Pattern.compile("/api/v1/products/([1-9][0-9]{0,8})");
static OptionalInt productId(String path) { Matcher m = PRODUCT.matcher(path); if (!m.matches()) { // the WHOLE path must match return OptionalInt.empty(); } return OptionalInt.of(Integer.parseInt(m.group(1))); // safe: at most 9 digits always fits in int }
public static void main(String[] args) { String[] paths = {"/api/v1/products/42", "/api/v1/products/abc", "/api/v1/products/0", "/api/v1/products/-5", "/api/v1/products/007", "/api/v1/products/99999999999", "/api/v1/products/42/reviews", "/api/v1/products/42/", "/api/v1/products/"}; for (String path : paths) { OptionalInt id = productId(path); System.out.printf("%-30s %s%n", path, id.isPresent() ? "id " + id.getAsInt() : "404 Not Found"); } }}/api/v1/products/42 id 42 /api/v1/products/abc 404 Not Found /api/v1/products/0 404 Not Found /api/v1/products/-5 404 Not Found /api/v1/products/007 404 Not Found /api/v1/products/99999999999 404 Not Found /api/v1/products/42/reviews 404 Not Found /api/v1/products/42/ 404 Not Found /api/v1/products/ 404 Not Found
What this code does
matcher(path).matches()is true only when the whole path fits, so/42/reviewsand/42/are rejected.[1-9][0-9]{0,8}refuses0,-5,007and numbers longer than 9 digits.- Because the group has at most 9 digits,
Integer.parseIntcan never overflow. Every rejected path becomes a clean404instead of a crash.
Integer.parseInt(path.substring(...)) throws NumberFormatException for all of those. The JDK server catches the exception from your handler, closes the connection without any response and prints nothing. The client sees only IOException: HTTP/1.1 header parser received no bytes, and you get no clue in the server console.
The safe way is the pattern /api/v1/products/([1-9][0-9]{0,8}). It accepts only a positive whole number without a sign or leading zero, at most 9 digits, so Integer.parseInt on the group can never fail. Anything else is "no such resource": 404.
Find the bug
Find the unsafe line
Click the line that lets a bad path through.
GET /api/v1/products/abc closes the connection with no answer. Which line causes it?
Round 1 of 2404 for unknown paths, 405 with an Allow header
405 + Allow is the answer for a known path used with the wrong method: status 405 Method Not Allowed plus an Allow header that lists the supported methods, such as Allow: GET, POST. An unknown path gets 404 Not Found.
Example 5 answers 404 for an unknown path and 405 with Allow for a wrong method, using plain if-else.
Example 5 · 404 and 405 by hand, with if-else
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;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;
public class MethodCheckDemo {
static void products(HttpExchange exchange) throws IOException { try (exchange) { String method = exchange.getRequestMethod(); String path = exchange.getRequestURI().getPath(); if (path.equals("/api/v1/products")) { if (method.equals("GET")) { send(exchange, 200, "list of products"); } else if (method.equals("POST")) { send(exchange, 201, "product created"); } else { exchange.getResponseHeaders().set("Allow", "GET, POST"); send(exchange, 405, method + " is not supported on this URL"); } } else if (path.matches("/api/v1/products/[1-9][0-9]{0,8}")) { if (method.equals("GET")) { send(exchange, 200, "one product"); } else if (method.equals("DELETE")) { exchange.sendResponseHeaders(204, -1); } else { exchange.getResponseHeaders().set("Allow", "GET, DELETE"); send(exchange, 405, method + " is not supported on this URL"); } } else { send(exchange, 404, "No resource at " + path); } } }
static void send(HttpExchange exchange, int status, String text) throws IOException { byte[] body = text.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8"); exchange.sendResponseHeaders(status, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/products", MethodCheckDemo::products); server.start();
String base = "http://127.0.0.1:" + server.getAddress().getPort(); HttpClient client = HttpClient.newHttpClient(); String[][] calls = {{"GET", "/api/v1/products"}, {"PUT", "/api/v1/products"}, {"DELETE", "/api/v1/products/7"}, {"POST", "/api/v1/products/7"}, {"GET", "/api/v1/products/abc"}, {"GET", "/api/v1/productsXYZ"}}; try { for (String[] call : calls) { HttpRequest request = HttpRequest.newBuilder(URI.create(base + call[1])) .method(call[0], HttpRequest.BodyPublishers.noBody()).build(); HttpResponse<String> r = client.send(request, HttpResponse.BodyHandlers.ofString()); String allow = r.headers().firstValue("Allow").map(a -> " [Allow: " + a + "]").orElse(""); String body = r.body().isEmpty() ? "" : " " + r.body(); System.out.printf("%-6s %-22s -> %d%s%s%n", call[0], call[1], r.statusCode(), body, allow); } } finally { server.stop(0); } }}GET /api/v1/products -> 200 list of products PUT /api/v1/products -> 405 PUT is not supported on this URL [Allow: GET, POST] DELETE /api/v1/products/7 -> 204 POST /api/v1/products/7 -> 405 POST is not supported on this URL [Allow: GET, DELETE] GET /api/v1/products/abc -> 404 No resource at /api/v1/products/abc GET /api/v1/productsXYZ -> 404 No resource at /api/v1/productsXYZ
What this code does
- One handler checks the path, then the method. A known path with an unknown method gets
405withAllow; an unknown path gets404.try (exchange)closes the exchange on every branch. - It works, but even two resources need nested if-else blocks, two hand-written
Allowlists and one regex. The next example moves all of that into a reusable router.
The difference helps the client. A 404 says "check the URL"; a 405 says "the URL is right, use one of these methods". Answering 404 for a wrong method, or 200 for every method, hides the mistake.
Written by hand, every handler needs an if-else for the path and, inside it, one for the method. With five resources and up to five methods each, that is a long, fragile chain, and it is easy to forget the Allow header in one branch.
A small Router class instead of if-else chains
A router keeps a list of routes (method, path template and code to run) and runs the first route whose path and method match. A matching path with another method gives 405; no matching path gives 404.
Example 6 builds a Router class with {id} templates, 404 and 405.
Example 6 · A Router with {id} templates, 404 and 405
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpHandler;import com.sun.net.httpserver.HttpServer;import java.io.IOException;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.ArrayList;import java.util.LinkedHashMap;import java.util.LinkedHashSet;import java.util.List;import java.util.Map;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern;
/** What a route runs: the exchange plus the path variables, such as {id=42}. */@FunctionalInterfaceinterface RouteHandler { void handle(HttpExchange exchange, Map<String, String> vars) throws IOException;}
/** One HttpHandler for every path: finds the route by method and path, or answers 404 / 405. */class Router implements HttpHandler {
private record Route(String method, Pattern path, List<String> names, RouteHandler handler) { }
private static final Pattern VARIABLE = Pattern.compile("\\{(\\w+)}"); private final List<Route> routes = new ArrayList<>();
/** "/api/v1/products/{id}" becomes the regex /api/v1/products/([1-9][0-9]{0,8}). */ Router add(String method, String template, RouteHandler handler) { List<String> names = new ArrayList<>(); Matcher m = VARIABLE.matcher(template); StringBuilder regex = new StringBuilder(); int last = 0; while (m.find()) { regex.append(Pattern.quote(template.substring(last, m.start()))).append("([1-9][0-9]{0,8})"); names.add(m.group(1)); last = m.end(); } regex.append(Pattern.quote(template.substring(last))); routes.add(new Route(method, Pattern.compile(regex.toString()), names, handler)); return this; }
@Override public void handle(HttpExchange exchange) throws IOException { try (exchange) { String path = exchange.getRequestURI().getPath(); Set<String> allowed = new LinkedHashSet<>(); for (Route route : routes) { Matcher m = route.path().matcher(path); if (!m.matches()) { continue; } if (route.method().equals(exchange.getRequestMethod())) { Map<String, String> vars = new LinkedHashMap<>(); for (int i = 0; i < route.names().size(); i++) { vars.put(route.names().get(i), m.group(i + 1)); } route.handler().handle(exchange, vars); return; } allowed.add(route.method()); } if (allowed.isEmpty()) { Text.send(exchange, 404, "No resource at " + path); } else { exchange.getResponseHeaders().set("Allow", String.join(", ", allowed)); Text.send(exchange, 405, exchange.getRequestMethod() + " is not supported on this URL"); } } }}
class Text { static void send(HttpExchange exchange, int status, String text) throws IOException { byte[] body = text.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8"); exchange.sendResponseHeaders(status, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }}
public class RouterDemo { public static void main(String[] args) throws IOException, InterruptedException { Router router = new Router() .add("GET", "/api/v1/products", (ex, vars) -> Text.send(ex, 200, "all products")) .add("POST", "/api/v1/products", (ex, vars) -> Text.send(ex, 201, "created")) .add("GET", "/api/v1/products/{id}", (ex, vars) -> Text.send(ex, 200, "product " + vars.get("id"))) .add("DELETE", "/api/v1/products/{id}", (ex, vars) -> Text.send(ex, 200, "deleted " + vars.get("id"))) .add("GET", "/api/v1/customers/{id}/orders", (ex, vars) -> Text.send(ex, 200, "orders of customer " + vars.get("id")));
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/", router); server.start();
String base = "http://127.0.0.1:" + server.getAddress().getPort(); HttpClient client = HttpClient.newHttpClient(); String[][] calls = {{"GET", "/api/v1/products/42"}, {"DELETE", "/api/v1/products/42"}, {"GET", "/api/v1/customers/2/orders"}, {"PATCH", "/api/v1/products/42"}, {"DELETE", "/api/v1/products"}, {"GET", "/api/v1/products/42/"}, {"GET", "/api/v1/orders"}}; try { for (String[] call : calls) { HttpRequest request = HttpRequest.newBuilder(URI.create(base + call[1])) .method(call[0], HttpRequest.BodyPublishers.noBody()).build(); HttpResponse<String> r = client.send(request, HttpResponse.BodyHandlers.ofString()); String allow = r.headers().firstValue("Allow").map(a -> " [Allow: " + a + "]").orElse(""); System.out.printf("%-6s %-27s -> %d %s%s%n", call[0], call[1], r.statusCode(), r.body(), allow); } } finally { server.stop(0); } }}GET /api/v1/products/42 -> 200 product 42 DELETE /api/v1/products/42 -> 200 deleted 42 GET /api/v1/customers/2/orders -> 200 orders of customer 2 PATCH /api/v1/products/42 -> 405 PATCH is not supported on this URL [Allow: GET, DELETE] DELETE /api/v1/products -> 405 DELETE is not supported on this URL [Allow: GET, POST] GET /api/v1/products/42/ -> 404 No resource at /api/v1/products/42/ GET /api/v1/orders -> 404 No resource at /api/v1/orders
What this code does
addturns each{name}of a template into a safe number group and remembers the names.handleruns the first route whose path and method match and passes the variables, such as{id=42}.- A matching path with another method adds that method to
Allow, soPATCH /api/v1/products/42gets405withAllow: GET, DELETE. A trailing slash or an unknown path gets404. The router is the only context, on/.
Each {id} in a template becomes the same safe pattern as before, ([1-9][0-9]{0,8}), and its value goes into a map such as {id=42}. Adding an endpoint is now one line: .add("GET", "/api/v1/products/{id}", handler). The 404 and 405 rules live in one place and work the same for every endpoint.
The same idea sits behind @GetMapping("/api/v1/products/{id}") in Spring: a table of routes plus one dispatcher. The ShopLite project of this module uses this Router, with JSON responses.
Order of execution
How the router handles a request
Put the steps in the order the router follows them.
Next step
Check your understanding
12 quick questions