Core Concepts
Request Handling
Soklet's primary aim is to map HTTP requests to Plain Old Java Methods (hereafter Resource Methods).
This is a Resource Method that handles GET /hello requests:
@GET("/hello")
public String helloWorld() {
return "Hello, world!";
}
@GET("/hello")
public String helloWorld() {
return "Hello, world!";
}
Soklet detects Resource Methods using a compile-time annotation processor and constructs a lookup table to avoid expensive classpath scans during startup.
Compile each Java module separately so it has its own generated indexes. A single javac invocation compiling multiple named modules is not supported. Ordinary classpath builds and separate Maven or Gradle module compilations remain supported.
When an HTTP request arrives, Soklet determines the appropriate Resource Method to invoke based on HTTP method and URL path pattern matching. Parameter values are injected using the heuristics described in Request Data below.
The built-in HTTP parser rejects transfer-coding parameters such as Transfer-Encoding: chunked;foo=bar with HTTP 400 and closes the connection before invoking a resource method. Send Transfer-Encoding: chunked without parameters. Valid extensions on individual chunk-size lines, such as 4;name=value, remain supported.
Resource Methods may return results of any type - Response Writing occurs downstream and is responsible for converting the returned objects to response body bytes sent over the wire.
For HEAD, Soklet prefers an explicit @HEAD method. Otherwise, it resolves the matching @GET method before lifecycle/metrics callbacks and request interception. These hooks and the simulator result identify that selected GET method. The handler still receives a HEAD request, and Soklet omits the response body without acquiring a streaming producer. Rewrites in wrapRequest are applied before this selection.
The Basics
Classes that contain Resource Methods are Plain Old Java Objects - no special interfaces to implement or superclasses to extend. Because Resource Methods may accept and return any types you like, they are amenable to automated testing.
The only requirement is that you decorate your method with an appropriate HTTP annotation like @GET so Soklet's annotation processor can find it.
public class ExampleResource {
// You can name your methods whatever you like
// and return whatever you like (or void for a 204 No Content).
@GET("/")
public String index() {
return "Hello, world!";
}
}
public class ExampleResource {
// You can name your methods whatever you like
// and return whatever you like (or void for a 204 No Content).
@GET("/")
public String index() {
return "Hello, world!";
}
}
Resource Methods must be decorated with one or more of the following annotations:
@GET@POST@PUT@PATCH@DELETE@HEAD@OPTIONS@SseEventSource(see Server-Sent Events for details)
MCP is configured separately from normal Resource Methods. Annotate endpoint classes with @McpServerEndpoint, then declare @McpTool, @McpPrompt, @McpResource, or @McpResourceList handlers. The annotation processor generates immutable endpoint descriptors. See the MCP documentation for the complete authoring model and current API references.
Each annotation can be repeated. For example:
@GET("/test")
@GET("/test-2")
@POST("/test")
public String test() {
// This responds to the 2 GET URLs and 1 POST URL
return "Multiple methods";
}
@GET("/test")
@GET("/test-2")
@POST("/test")
public String test() {
// This responds to the 2 GET URLs and 1 POST URL
return "Multiple methods";
}
Unless you explicitly specify Resource Methods with @HEAD or @OPTIONS, Soklet will provide sensible default implementations for each.
Your Resource Methods can return any type you like, or void or null or Optional<T>::empty for an HTTP 204. Any Optional<T> instances will be unwrapped.
If you need to specify an HTTP status code, headers, or cookies, you can return an instance of Soklet's Response type.
If you need to say "send exactly these bytes in the response body" (e.g. serving up a binary file or using Servlet Integration), you can return an instance of Soklet's MarshaledResponse type.
// HTTP 204
@GET("/no-op")
public void noOp() {
// Don't do anything
}
// Return any standard JDK type you like...
@GET("/hardcoded-map")
public Map<String, Object> hardcodedMap() {
return Map.of("example", List.of(1, 2, 3));
}
public record AccountResponse (
UUID id,
String emailAddress,
Locale locale
) {}
// ...or define your own.
@GET("/accounts/{id}")
public AccountResponse findAccount(@PathParameter UUID id) {
// Error checking elided
Account account = myBackend.findAccount(id);
return new AccountResponse(
account.getId(),
account.getEmailAddress(),
account.getLocale()
);
}
// Return the Response type if you need fine-grained control
@POST("/detailed-response")
public Response detailedResponse() {
UUID id = myBackend.createRecord();
// HTTP 201 Created
return Response.withStatusCode(201)
.headers(Map.of(
"X-Example", List.of("testing")
))
.cookies(List.of(
ResponseCookie.with("test", "abc")
.httpOnly(true)
.secure(true)
.maxAge(Duration.ofMinutes(5))
.sameSite(SameSite.LAX)
.build()
))
.body(Map.of("id", id))
.build();
}
@GET("/example-redirect")
public Response exampleRedirect() {
// Here we use a convenience builder for performing redirects.
// You could alternatively do this "by hand" by setting HTTP status
// and headers appropriately.
return Response.withRedirect(
RedirectType.HTTP_307_TEMPORARY_REDIRECT, "/other-url"
).build();
}
// Use MarshaledResponse to serve up binary data
@GET("/example-image.png")
public MarshaledResponse exampleImage() {
Path imageFile = Path.of("/home/user/test.png");
return MarshaledResponse.withStatusCode(200)
.body(imageFile)
.headers(Map.of(
"Content-Type", List.of("image/png")
))
.build();
}
// HTTP 204
@GET("/no-op")
public void noOp() {
// Don't do anything
}
// Return any standard JDK type you like...
@GET("/hardcoded-map")
public Map<String, Object> hardcodedMap() {
return Map.of("example", List.of(1, 2, 3));
}
public record AccountResponse (
UUID id,
String emailAddress,
Locale locale
) {}
// ...or define your own.
@GET("/accounts/{id}")
public AccountResponse findAccount(@PathParameter UUID id) {
// Error checking elided
Account account = myBackend.findAccount(id);
return new AccountResponse(
account.getId(),
account.getEmailAddress(),
account.getLocale()
);
}
// Return the Response type if you need fine-grained control
@POST("/detailed-response")
public Response detailedResponse() {
UUID id = myBackend.createRecord();
// HTTP 201 Created
return Response.withStatusCode(201)
.headers(Map.of(
"X-Example", List.of("testing")
))
.cookies(List.of(
ResponseCookie.with("test", "abc")
.httpOnly(true)
.secure(true)
.maxAge(Duration.ofMinutes(5))
.sameSite(SameSite.LAX)
.build()
))
.body(Map.of("id", id))
.build();
}
@GET("/example-redirect")
public Response exampleRedirect() {
// Here we use a convenience builder for performing redirects.
// You could alternatively do this "by hand" by setting HTTP status
// and headers appropriately.
return Response.withRedirect(
RedirectType.HTTP_307_TEMPORARY_REDIRECT, "/other-url"
).build();
}
// Use MarshaledResponse to serve up binary data
@GET("/example-image.png")
public MarshaledResponse exampleImage() {
Path imageFile = Path.of("/home/user/test.png");
return MarshaledResponse.withStatusCode(200)
.body(imageFile)
.headers(Map.of(
"Content-Type", List.of("image/png")
))
.build();
}
How to turn Resource Method return values into a final over-the-wire representation (JSON, Protocol Buffers, Thrift, file-backed response bodies, ...) is generally not the concern of your Resource Method - that happens downstream. See Response Writing for details.
Request Data
Soklet will detect and automatically inject Resource Method parameters of type Request. This enables programmatic access to all aspects of the HTTP request.
@GET("/example")
public void example(Request request /* param name is arbitrary */) {
// Request ID (generated by the configured IdGenerator)
Object requestId = request.getId();
// Here, it would be HttpMethod.GET
HttpMethod httpMethod = request.getHttpMethod();
// The decoded path, e.g. "/example"
String path = request.getPath();
// The path exactly as the client specified,
// e.g. "/a%20b" (never decoded)
String rawPath = request.getRawPath();
// Decoded query parameter values by name
Map<String, List<String>> queryParameters = request.getQueryParameters();
// Shorthand that requires at most one query parameter occurrence by name
Optional<String> queryParameter = request.getQueryParameter("test");
// The query exactly as the client specified,
// e.g. "a=b&c=d+e" (never decoded).
// Useful for special cases like HMAC signature
// verification, which might rely on exact client format
Optional<String> rawQuery = request.getRawQuery();
// The path + query exactly as the client specified,
// e.g. "/my%20path?a=b&c=d%20e" (never decoded)
String rawPathAndQuery = request.getRawPathAndQuery();
// Raw socket peer address (which might be a proxy), if available
Optional<InetSocketAddress> remoteAddress = request.getRemoteAddress();
// Handler-visible request body bytes, if present
Optional<byte[]> body = request.getBody();
// Encoded payload size before transparent Content-Encoding decompression
int encodedBodySizeInBytes = request.getEncodedBodySizeInBytes();
// Request body marshaled to a string, if present.
// Charset defined in "Content-Type" header is used to marshal.
// If not specified, UTF-8 is assumed
Optional<String> bodyAsString = request.getBodyAsString();
// Was the request too large to read fully?
boolean contentTooLarge = request.isContentTooLarge();
// Header values by name (names are case-insensitive)
Map<String, List<String>> headers = request.getHeaders();
// Shorthand that requires at most one header occurrence by name (case-insensitive)
Optional<String> header = request.getHeader("Accept-Language");
// Parsed W3C trace context from traceparent/tracestate, if present
Optional<TraceContext> traceContext = request.getTraceContext();
// Request cookies by name
Map<String, List<String>> cookies = request.getCookies();
// Shorthand that requires at most one cookie occurrence by name
Optional<String> cookie = request.getCookie("cookie-name");
// Decoded form parameters by name (application/x-www-form-urlencoded)
Map<String, List<String>> fps = request.getFormParameters();
// Shorthand that requires at most one form parameter occurrence by name
Optional<String> fp = request.getFormParameter("fp-name");
// Is this a multipart request?
boolean multipart = request.isMultipart();
// Decoded multipart fields by name
Map<String, List<MultipartField>> mpfs = request.getMultipartFields();
// Shorthand that requires at most one multipart field occurrence by name
Optional<MultipartField> mpf = request.getMultipartField("file-input");
// CORS information, if present
Optional<Cors> cors = request.getCors();
// CORS preflight information, if present
Optional<CorsPreflight> corsPreflight = request.getCorsPreflight();
// Ordered locales via Accept-Language parsing
List<Locale> locales = request.getLocales();
// Ordered language ranges via Accept-Language parsing
List<LanguageRange> lrs = request.getLanguageRanges();
// Ordered media ranges via Accept parsing; empty means no Accept preference
List<MediaRange> mediaRanges = request.getMediaRanges();
// Charset as specified by "Content-Type" header, if present
Optional<Charset> charset = request.getCharset();
// Content type component of "Content-Type" header, if present
Optional<String> contentType = request.getContentType();
}
@GET("/example")
public void example(Request request /* param name is arbitrary */) {
// Request ID (generated by the configured IdGenerator)
Object requestId = request.getId();
// Here, it would be HttpMethod.GET
HttpMethod httpMethod = request.getHttpMethod();
// The decoded path, e.g. "/example"
String path = request.getPath();
// The path exactly as the client specified,
// e.g. "/a%20b" (never decoded)
String rawPath = request.getRawPath();
// Decoded query parameter values by name
Map<String, List<String>> queryParameters = request.getQueryParameters();
// Shorthand that requires at most one query parameter occurrence by name
Optional<String> queryParameter = request.getQueryParameter("test");
// The query exactly as the client specified,
// e.g. "a=b&c=d+e" (never decoded).
// Useful for special cases like HMAC signature
// verification, which might rely on exact client format
Optional<String> rawQuery = request.getRawQuery();
// The path + query exactly as the client specified,
// e.g. "/my%20path?a=b&c=d%20e" (never decoded)
String rawPathAndQuery = request.getRawPathAndQuery();
// Raw socket peer address (which might be a proxy), if available
Optional<InetSocketAddress> remoteAddress = request.getRemoteAddress();
// Handler-visible request body bytes, if present
Optional<byte[]> body = request.getBody();
// Encoded payload size before transparent Content-Encoding decompression
int encodedBodySizeInBytes = request.getEncodedBodySizeInBytes();
// Request body marshaled to a string, if present.
// Charset defined in "Content-Type" header is used to marshal.
// If not specified, UTF-8 is assumed
Optional<String> bodyAsString = request.getBodyAsString();
// Was the request too large to read fully?
boolean contentTooLarge = request.isContentTooLarge();
// Header values by name (names are case-insensitive)
Map<String, List<String>> headers = request.getHeaders();
// Shorthand that requires at most one header occurrence by name (case-insensitive)
Optional<String> header = request.getHeader("Accept-Language");
// Parsed W3C trace context from traceparent/tracestate, if present
Optional<TraceContext> traceContext = request.getTraceContext();
// Request cookies by name
Map<String, List<String>> cookies = request.getCookies();
// Shorthand that requires at most one cookie occurrence by name
Optional<String> cookie = request.getCookie("cookie-name");
// Decoded form parameters by name (application/x-www-form-urlencoded)
Map<String, List<String>> fps = request.getFormParameters();
// Shorthand that requires at most one form parameter occurrence by name
Optional<String> fp = request.getFormParameter("fp-name");
// Is this a multipart request?
boolean multipart = request.isMultipart();
// Decoded multipart fields by name
Map<String, List<MultipartField>> mpfs = request.getMultipartFields();
// Shorthand that requires at most one multipart field occurrence by name
Optional<MultipartField> mpf = request.getMultipartField("file-input");
// CORS information, if present
Optional<Cors> cors = request.getCors();
// CORS preflight information, if present
Optional<CorsPreflight> corsPreflight = request.getCorsPreflight();
// Ordered locales via Accept-Language parsing
List<Locale> locales = request.getLocales();
// Ordered language ranges via Accept-Language parsing
List<LanguageRange> lrs = request.getLanguageRanges();
// Ordered media ranges via Accept parsing; empty means no Accept preference
List<MediaRange> mediaRanges = request.getMediaRanges();
// Charset as specified by "Content-Type" header, if present
Optional<Charset> charset = request.getCharset();
// Content type component of "Content-Type" header, if present
Optional<String> contentType = request.getContentType();
}
These maps and their lists are immutable snapshots. Lists preserve every occurrence in per-name order, including identical repeated values. Header names are case insensitive; query, form, and cookie names are case sensitive. Single-value accessors and scalar annotation parameters reject repeated values, even when they are identical. Use List<T> parameters when repetition is allowed.
An explicit empty cookie such as session= retains one empty value, just like session="". session=; session=value therefore has two occurrences and is rejected by scalar access or binding. Bare tokens without = keep their existing valueless behavior.
For request headers, each List entry is one complete field occurrence. A single Accept-Encoding: gzip, deflate, br is represented as List.of("gzip, deflate, br"); commas are not automatically split. Surrounding HTTP spaces and tabs are removed in both physical and map-backed requests, and empty field values are retained. request.getHeader(...) returns Optional.of("") for one empty field and rejects multiple occurrences, including repeated empties.
Leading slashes remain part of the raw request path. For //x/admin, request.getRawPath() returns //x/admin, while the decoded, normalized request.getPath() returns /x/admin. Routing retains the x component.
This normalization applies to requests read from the wire and to Request.withRawUrl(...). Request.withPath(...) and copy().path(...) use the decoded path exactly as given: ., .., // and a trailing slash are kept. Use withRawUrl when a test needs the path the wire would deliver.
Raw HTTP request targets reject literal #, including after a query value. Use %23 to send a hash character. Decoded Request.withPath(...) path/query values accept hashes and encode them when building the raw target.
Notes on Ordering and Case-Sensitivity
All Map keysets above are guaranteed to reflect the order in which the data was specified in the request. For example, given a query string test=a&last=b, the keyset's iteration order is test, last.
Further, per HTTP spec, all Map keysets are case-sensitive with the exception of request headers.
For example, these invocations are equivalent:
But these are not!
...and neither are these:
Accessing the Request directly is useful for scenarios where you don't know the structure of your requests at compile time.
But for the common case - where you know ahead-of-time what your requests should look like - it's preferable to take advantage of Soklet's Resource Method parameter annotations, which enable static typing via Value Conversions, throw helpful exceptions in the face of invalid input, and improve code reuse/testability by making your Resource Methods be "Just Another Java Method". Read on for details.
Explicit empty query and form names, such as =value, appear under the empty string key in their maps. Empty segments between & separators are ignored. Single blank values still convert to Optional.empty() under default annotation binding; repeated values still fail scalar binding.
Request Text Decoding
Request.getLocales() and getLanguageRanges() ignore empty Accept-Language list members, so en,,fr preserves both preferences. Parsing is bounded to 4,096 combined characters and 32 comma-separated members, including empty members. Malformed nonempty ranges or excessive input produce an empty list.
Multipart field names and ordinary quoted filenames retain literal percent-escape spellings such as %22. Browser escaping can produce the same spelling for a quote and for literal %22 text, so Soklet does not guess which original value was intended. Multipart names are separate from URL query/form percent decoding. Header text must be valid UTF-8. Non-browser clients that default to raw ISO-8859-1 multipart header bytes must select UTF-8 or RFC 5987 extended parameters for non-ASCII names. Each header accepts at most 128 parameter tokens, including the initial disposition/media token, and each metadata value at most 128 encoded words. Unknown charset names and malformed encoded words retain literal fallback without repeated provider discovery or exception allocation.
Named HTML entities in filenames remain literal: a&b.txt stays unchanged. Numeric references such as   retain legacy-client compatibility; decoded control characters, surrogate values, and invalid code points are rejected. An empty body has no multipart fields. For a nonempty body, absence of any valid opening delimiter produces HTTP 400 when parsed. A preamble may precede the opening delimiter. A boundary-like candidate with an invalid suffix is malformed, even if a later candidate would be valid. Space/tab delimiter padding is accepted. The closing delimiter must end at EOF or with a line ending; arbitrary bytes appended directly after its closing -- are rejected.
Soklet rejects malformed request text with HTTP 400 Bad Request by default. It does not silently substitute replacement characters. This applies to percent-decoded paths and query/form parameters, cookie values, request-body text, multipart metadata, and multipart field text. Valid Unicode, including a deliberately encoded U+FFFD replacement character, is accepted.
Malformed paths and queries can fail before Soklet has a valid Request or invokes a resource method. On standard HTTP, those failures use ResponseMarshaler::forUnparsedRequest, rather than the ordinary resource exception path. Do not rely on normal CORS response finalization or readable browser error bodies for these early rejections. Percent-encoded slashes in paths (%2F, case-insensitive) are rejected; use literal / path separators rather than encoding a slash inside a path parameter. Query values may still contain an encoded slash.
Paths, query parameters, and cookie values use UTF-8. Request.getBodyAsString() and MultipartField.getDataAsString() honor the selected charset and default to UTF-8. Form percent-escapes use the body's selected charset. Cookie + characters remain literal; malformed cookie percent-escapes such as %ZZ remain literal text, while %FF is rejected because it encodes an invalid UTF-8 byte.
For non-ASCII cookie text, percent-encode its UTF-8 bytes before sending it, for example with browser encodeURIComponent. UTF-8 percent decoding does not make raw UTF-8 bytes in a Cookie header portable; those bytes can arrive as different characters. Keep cookie names and the transmitted value ASCII.
RFC 2231 extended parameters and RFC 2047 encoded words use only the standard UTF-8, ISO-8859-1, US-ASCII, UTF-16, UTF-16BE and UTF-16LE charsets and their recognized aliases. Unsupported charset names leave the original parameter text unchanged. This bounds decoding work for untrusted multipart metadata; it does not change raw field bytes.
Extended multipart parameters such as name* and filename* require complete ASCII hexadecimal percent-escapes. Malformed or truncated escapes and raw non-ASCII characters in those encoded parameters are rejected with HTTP 400; valid percent-encoded Unicode remains supported.
The Content-Type charset parameter can appear after other parameters and can be quoted, for example text/plain; profile="example;v=1"; charset="ISO-8859-1". Multiple charset parameters are rejected with HTTP 400, including identical duplicates. A single invalid or unsupported charset keeps the UTF-8 fallback.
HTML form bodies are parsed directly as &-separated pairs. Literal #, spaces, quotes, and similar characters are retained as data; they do not truncate later fields or fail URL parsing. Low-level form names and values are not trimmed. A bare name or name= contributes one empty value, and repeated empty values remain separate occurrences. The default annotation value converter still trims strings and maps a single blank value to Optional.empty() for Optional<T> parameters; repeated blanks still fail scalar binding.
ASCII-compatible form charsets such as UTF-8 support mixed literal and percent-encoded bytes. Non-ASCII-compatible charsets such as UTF-16 require every name/value byte to be percent-encoded, leaving the & and = delimiters as ASCII. Stateful ISO-2022 charsets require escape/shift bytes (ESC, SO, and SI) and non-ASCII bytes to be percent-encoded. Ambiguous raw encodings raise IllegalRequestException when form parameters are accessed, producing HTTP 400 with the default response marshaler. Request-body text decoding remains independent of form parsing.
Path and query validation happens when a request is constructed, including query values that a handler never reads. Body, form, cookie, and multipart decoding remains lazy. Failures use IllegalRequestException or IllegalRequestBodyException with redacted decoding diagnostics. Use Request.getBody() or MultipartField.getData() for binary payloads or application-defined decoding; these methods preserve the raw bytes.
Decoded query names and values supplied to Request.withPath(...) or a request copier also reject unpaired UTF-16 surrogates. Query encoding and RFC 8187 header parameter construction validate that text before encoding; valid supplementary characters and explicit U+FFFD remain supported.
Binding Declaration Rules
Apply only one Soklet binding annotation to each Java parameter: @PathParameter, @QueryParameter, @FormParameter, @RequestHeader, @RequestCookie, @Multipart or @RequestBody. Custom qualifier annotations can accompany a binding. For query, form, header, cookie and multipart bindings, optional=true requires a reference type such as Integer or Optional<Integer>; an optional primitive such as int is rejected. Required primitives remain supported. An optional @RequestBody retains the Java primitive default when the body is absent or its marshaler returns no value, including blank numeric bodies handled by the default converter. Malformed bodies still fail with HTTP 400. Required scalar query, form, header and cookie bindings also fail with HTTP 400 if their converter returns no value. The processor reports invalid bindings on the parameter, and the default parameter provider checks explicit registrations during setup and dynamically resolved methods before instance acquisition. Custom parameter providers retain control of their runtime bindings. With default value conversion, absent or single blank Optional<T> value bindings still produce Optional.empty().
Binding Failure Diagnostics
Default missing-value and conversion-failure messages omit request names and values. Applications can inspect the structured accessors on conversion failures:
The value accessors return Optional<String> and expose request data. Keep generic error responses and routine logs free of these values. Request-body conversion failures identify the target Java type; the original body remains available from Request.getBody() on the request supplied to error handling. Custom converters, marshalers and exception handlers control their own diagnostics.
Query Parameters
Soklet will inject query parameter values for Resource Method parameters decorated with the @QueryParameter annotation.
// This URL might look like /query-params?date=2022-09-21&value=ABC&value=123
@GET("/query-params")
public String queryParamsExample(
@QueryParameter LocalDate date,
@QueryParameter(name="value", optional=true) List<String> values
) {
return String.format("date=%s, values=%s", date, values);
}
// This URL might look like /query-params?date=2022-09-21&value=ABC&value=123
@GET("/query-params")
public String queryParamsExample(
@QueryParameter LocalDate date,
@QueryParameter(name="value", optional=true) List<String> values
) {
return String.format("date=%s, values=%s", date, values);
}
By default, Soklet will assume the query parameter name is identical to the Java method parameter name. This behavior can be overridden by supplying an explicit name, e.g. @QueryParameter(name="query_param_name"). Query parameter names are case-sensitive.
If the query parameter can be specified multiple times, it must be declared as a List<T>.
If a query parameter is not required, it must have the @QueryParameter(optional=true) annotation element specified or be wrapped in an Optional<T> value, otherwise Soklet will throw a MissingQueryParameterException if not supplied.
MissingQueryParameterException: A required query parameter was not specified.
MissingQueryParameterException: A required query parameter was not specified.
If a query parameter is invalid, Soklet will throw an IllegalQueryParameterException.
IllegalQueryParameterException: A query parameter could not be converted to the resource method parameter type.
IllegalQueryParameterException: A query parameter could not be converted to the resource method parameter type.
See Value Conversions for details on how Soklet marshals query parameter string values to "complex" types like LocalDate, and how you can customize this behavior.
See Response Writing - Uncaught Exceptions for details on how to catch these exceptions and communicate them back to the client.
Heads Up!
Soklet decodes query parameters according to QueryFormat.RFC_3986_STRICT semantics. A literal + remains a plus sign; encode a space as %20 and a plus sign as %2B.
HTML forms submitted with GET and JavaScript URLSearchParams serialize spaces as +. That encoding differs from Soklet's query default: ?q=a+b reaches the handler as a+b, not a b. For query URLs, encode individual names and values with encodeURIComponent, which uses %20 for spaces. For HTML forms that need form decoding, use POST with application/x-www-form-urlencoded; see Form Parameters.
Path Parameters
Curly-brace syntax is used to denote path parameters.
// This URL might look like /example/123
@GET("/example/{placeholder}")
public Response examplePlaceholder(@PathParameter Integer placeholder) {
return Response.withStatusCode(204)
.headers(
Map.of("X-Placeholder-Header", List.of(String.valueOf(placeholder)))
)
.build();
}
// This URL might look like /example/123
@GET("/example/{placeholder}")
public Response examplePlaceholder(@PathParameter Integer placeholder) {
return Response.withStatusCode(204)
.headers(
Map.of("X-Placeholder-Header", List.of(String.valueOf(placeholder)))
)
.build();
}
All parameters in a path must have unique names and should have corresponding @PathParameter-annotated Java method parameters.
Each placeholder must occupy an entire slash-delimited component: /users/{id} is valid, while /users/prefix{id} and /users/{id}suffix are invalid. Empty, nested and unbalanced placeholders are also invalid. A varargs placeholder such as {tail*} must be the final component; its name cannot duplicate a simple placeholder name, so /{id}/{id*} is invalid. The annotation processor reports these errors on the annotated method, including repeatable route declarations. ResourcePathDeclaration.fromPath(...) and explicit class/method resolvers enforce the same syntax rules during construction or setup.
Route declarations and the ResourcePathDeclaration and ResourcePath factories reject unpaired UTF-16 surrogates. Valid supplementary Unicode characters retain their identity in generated indexes and runtime routing.
By default, Soklet will assume the path parameter name is identical to the Java method parameter name. This behavior can be overridden by supplying an explicit name, e.g. @PathParameter(name="path_param_name"). Path parameter names are case-sensitive.
There is no concept of a missing/optional path parameter. In that scenario, no Resource Method would match the request and processing would fall to Soklet's 404 Not Found handler.
A @PathParameter cannot use Optional<T>. A varargs path parameter must use String; custom converter targets remain supported for ordinary path parameters.
If a path parameter is invalid, Soklet will throw an IllegalPathParameterException.
IllegalPathParameterException: A path parameter could not be converted to the resource method parameter type.
IllegalPathParameterException: A path parameter could not be converted to the resource method parameter type.
See Value Conversions for details on how Soklet marshals path parameter string values to "complex" types like LocalDate, and how you can customize this behavior.
See Response Writing - Uncaught Exceptions for details on how to catch these exceptions and communicate them back to the client.
Varargs Path Parameters
A special case of @PathParameter is the ability to "collect" a path suffix of arbitrary depth by ending the path parameter name with a * character. This construct, called a Varargs Path Parameter, is useful for serving static files.
For example, this Resource Method path declaration /static/images/{imagePath*} would match paths like:
/static/images/test.jpeg/static/images/flags/pt-BR.png/static/images/deep/path/example.gif
Varargs placeholders match zero or more components. This declaration also matches /static/images and /static/images/; with the default parameter provider and String converter, imagePath is "" for those requests. Likewise, /{path*} matches / and injects "". Explicitly configured String converters still receive the empty suffix and may reject it. Nonempty suffixes retain their normal conversion behavior.
A matching fixed route takes precedence over the varargs route. If your handler requires a nonempty suffix, check it and return an appropriate response. For example, the StaticFiles handler below returns 404 when no file is selected.
A simple Resource Method that serves files from disk can delegate path safety, cache validators, and range requests to StaticFiles. Construct and retain the handler once for the application lifetime (for example, in a singleton resource or application configuration). The explicit trustedImmutableRoot(true) opt-in asserts that untrusted code cannot modify the root, its ancestors, or its contents while serving requests.
public final class ImageResource {
private static final StaticFiles STATIC_FILES = StaticFiles
.withRoot(Path.of("web/public/images"))
.trustedImmutableRoot(true)
.build();
@GET("/static/images/{imagePath*}")
public MarshaledResponse staticImage(
Request request,
@PathParameter String imagePath
) {
return STATIC_FILES.marshaledResponseFor(imagePath, request)
.orElseGet(() -> MarshaledResponse.fromStatusCode(404));
}
}
public final class ImageResource {
private static final StaticFiles STATIC_FILES = StaticFiles
.withRoot(Path.of("web/public/images"))
.trustedImmutableRoot(true)
.build();
@GET("/static/images/{imagePath*}")
public MarshaledResponse staticImage(
Request request,
@PathParameter String imagePath
) {
return STATIC_FILES.marshaledResponseFor(imagePath, request)
.orElseGet(() -> MarshaledResponse.fromStatusCode(404));
}
}
Heads Up!
A Resource Method path declaration can have at most one Varargs Path Parameter and, if present, it must be the final path component.
Legal path declarations:
/static/images/{imagePath*}/widgets/{widgetId}/{suffix*}
Illegal path declarations:
/static/{imagePath*}/temp/static/{prefix*}/images/{imagePath*}
When several varargs declarations match, Soklet compares their components from left to right: a literal outranks a single-component placeholder, which outranks the varargs suffix. For example, /widgets/{widgetId}/{suffix*} receives /widgets/42/details when /{path*} is also registered. At the first differing component, /a/b/{suffix*} wins over /a/{id}/c/{suffix*} for /a/b/c/file.
Matching declarations without varargs take precedence. Among those declarations, fewer placeholders and then more literals are preferred. Equally specific overlapping routes are rejected at compilation and resolver construction; registration order and placeholder names do not choose a handler. Each HTTP method and the HTTP/SSE transports are considered separately.
Cookies
Soklet will inject cookie values for Resource Method parameters decorated with the @RequestCookie annotation.
@GET("/request-cookies")
public String requestCookiesExample(
@RequestCookie LocalDate date,
@RequestCookie(name="value", optional=true) List<String> values
) {
return String.format("date=%s, values=%s", date, values);
}
@GET("/request-cookies")
public String requestCookiesExample(
@RequestCookie LocalDate date,
@RequestCookie(name="value", optional=true) List<String> values
) {
return String.format("date=%s, values=%s", date, values);
}
By default, Soklet will assume the cookie name is identical to the Java method parameter name. This behavior can be overridden by supplying an explicit name, e.g. @RequestCookie(name="cookie_name"). Cookie names are case-sensitive.
If the cookie can be specified multiple times, it must be declared as a List<T>.
If a cookie is not required, it must have the @RequestCookie(optional=true) annotation element specified or be wrapped in an Optional<T> value, otherwise Soklet will throw a MissingRequestCookieException if not supplied.
MissingRequestCookieException: A required request cookie was not specified.
MissingRequestCookieException: A required request cookie was not specified.
If a cookie is invalid, Soklet will throw an IllegalRequestCookieException.
IllegalRequestCookieException: A request cookie could not be converted to the resource method parameter type.
IllegalRequestCookieException: A request cookie could not be converted to the resource method parameter type.
See Value Conversions for details on how Soklet marshals request cookie string values to "complex" types like LocalDate, and how you can customize this behavior.
See Response Writing - Uncaught Exceptions for details on how to catch these exceptions and communicate them back to the client.
Headers
Soklet will inject header values for Resource Method parameters decorated with the @RequestHeader annotation.
@GET("/request-headers")
public String requestHeadersExample(
@RequestHeader(name="Accept-Encoding", optional=true) String acceptEncoding
) {
return String.format("Accept-Encoding is %s", acceptEncoding);
}
@GET("/request-headers")
public String requestHeadersExample(
@RequestHeader(name="Accept-Encoding", optional=true) String acceptEncoding
) {
return String.format("Accept-Encoding is %s", acceptEncoding);
}
By default, Soklet will assume the header name is identical to the Java method parameter name. This behavior can be overridden by supplying an explicit name, e.g. @RequestHeader(name="header_name"). Header names are case-insensitive.
If the header can be specified multiple times, it must be declared as a List<T>. One comma-separated field, such as Accept-Encoding: gzip, deflate, br, is still one occurrence, so the String parameter above receives its whole value. An annotated List<String> receives one complete string per occurrence. Use field-specific parsing for comma lists, such as request.getMediaRanges() for Accept and request.getLocales() for Accept-Language.
With the default value converter, a single empty or blank field binds to Optional.empty() for an Optional<T> parameter. Repeated fields fail scalar binding even when their values are identical or blank.
If a header is not required, it must have the @RequestHeader(optional=true) annotation element specified or be wrapped in an Optional<T> value, otherwise Soklet will throw a MissingRequestHeaderException if not supplied.
MissingRequestHeaderException: A required request header was not specified.
MissingRequestHeaderException: A required request header was not specified.
If a header is invalid, Soklet will throw an IllegalRequestHeaderException.
IllegalRequestHeaderException: A request header could not be converted to the resource method parameter type.
IllegalRequestHeaderException: A request header could not be converted to the resource method parameter type.
See Value Conversions for details on how Soklet marshals request header string values to "complex" types like LocalDate, and how you can customize this behavior.
See Response Writing - Uncaught Exceptions for details on how to catch these exceptions and communicate them back to the client.
Request Body
Soklet will inject the request body for Resource Method parameters decorated with the @RequestBody annotation. The name of the annotated parameter is arbitrary.
String, byte[], and a number of other JDK types as specified in Value Conversions are supported by default.
For the standard HTTP server, clients may use Expect: 100-continue with fixed-length or chunked request bodies. Soklet validates the request line and headers, sends the interim 100 Continue response when it is ready to receive the body, and rejects unsupported expectations with 417 Expectation Failed.
Transfer encoding requires HTTP/1.1. HTTP/1.0 requests containing Transfer-Encoding, duplicate Content-Length fields, and requests with both length and transfer-encoding fields are rejected with HTTP 400 and a closed connection. Chunk sizes must be hexadecimal digits; chunk extensions must use valid token or quoted-string syntax. Valid extensions are ignored when decoding the body. Malformed framing is rejected before a resource method runs.
Bare carriage returns are rejected in HTTP and SSE request lines and headers. SSE handshakes also reject folded or whitespace-only header lines, transfer encoding, repeated content-length fields, and any content length other than an unsigned decimal zero. A leading-zero value such as 000 is allowed.
// Request body as string
@POST("/rb-string")
public void requestBody(@RequestBody String requestBody) {
System.out.println(requestBody);
}
// Use optional=true or Optional<T> if request body is not required
@POST("/rb-optional-string")
public void requestBody(
@RequestBody(optional=true) String optionalRequestBody1,
@RequestBody Optional<String> optionalRequestBody2
) {
// This value can be null
System.out.println(optionalRequestBody1);
// This value is never null, but can be Optional.empty()
System.out.println(optionalRequestBody2);
}
// Can also get access to the raw bytes
@POST("/rb-bytes")
public void requestBody(@RequestBody byte[] requestBody) {
System.out.printf("%d bytes\n", requestBody.length);
}
// Complex types are supported.
// Example: a request body of "2024-10-31" without the quotes
@POST("/rb-date")
public void requestBody(@RequestBody LocalDate date) {
System.out.println(date);
}
// Primitive types are supported.
// Exmaple: a request body of "123" without the quotes
@POST("/rb-primitive-int")
public void requestBody(@RequestBody int primitiveType) {
System.out.println(primitiveType);
}
// Request body as string
@POST("/rb-string")
public void requestBody(@RequestBody String requestBody) {
System.out.println(requestBody);
}
// Use optional=true or Optional<T> if request body is not required
@POST("/rb-optional-string")
public void requestBody(
@RequestBody(optional=true) String optionalRequestBody1,
@RequestBody Optional<String> optionalRequestBody2
) {
// This value can be null
System.out.println(optionalRequestBody1);
// This value is never null, but can be Optional.empty()
System.out.println(optionalRequestBody2);
}
// Can also get access to the raw bytes
@POST("/rb-bytes")
public void requestBody(@RequestBody byte[] requestBody) {
System.out.printf("%d bytes\n", requestBody.length);
}
// Complex types are supported.
// Example: a request body of "2024-10-31" without the quotes
@POST("/rb-date")
public void requestBody(@RequestBody LocalDate date) {
System.out.println(date);
}
// Primitive types are supported.
// Exmaple: a request body of "123" without the quotes
@POST("/rb-primitive-int")
public void requestBody(@RequestBody int primitiveType) {
System.out.println(primitiveType);
}
If the request body is not required, it must have the @RequestBody(optional=true) annotation element specified or be wrapped in an Optional<T> value, otherwise Soklet will throw a MissingRequestBodyException if not supplied.
MissingRequestBodyException: A request body is required for this resource.
MissingRequestBodyException: A request body is required for this resource.
If the request body content is invalid, Soklet will throw an IllegalRequestBodyException.
IllegalRequestBodyException: Unable to marshal the request body to class java.time.LocalDate.
IllegalRequestBodyException: Unable to marshal the request body to class java.time.LocalDate.
Custom Request Body Parsing
In practice, request bodies are often specially-encoded payloads, e.g. JSON objects or XML documents. Soklet provides a hook for parsing request body types via the RequestBodyMarshaler functional interface:
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).requestBodyMarshaler(new RequestBodyMarshaler() {
// This example uses Google's GSON
static final Gson GSON = new Gson();
@NonNull
@Override
public Optional<Object> marshalRequestBody(
@NonNull Request request,
@NonNull ResourceMethod resourceMethod,
@NonNull Parameter parameter,
@NonNull Type requestBodyType
) {
// Let GSON turn the request body into an instance
// of the specified type.
//
// Note that this method has access to all runtime information
// about the request, which provides the opportunity to, for example,
// examine annotations on the method/parameter which might
// inform custom marshaling strategies.
String body = request.getBodyAsString()
.filter(value -> !value.isBlank())
.orElseThrow(() -> new IllegalRequestBodyException(
"Request body must contain JSON."
));
try {
Object value = GSON.fromJson(body, requestBodyType);
if (value == null)
throw new IllegalRequestBodyException(
"Request body must contain a non-null JSON value."
);
return Optional.of(value);
} catch (JsonParseException e) {
// Expected parse failures are client errors. Keep request data and
// the parser's input-bearing cause out of the public diagnostic.
throw new IllegalRequestBodyException(
"Request body is not valid JSON."
);
}
}
}).build();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).requestBodyMarshaler(new RequestBodyMarshaler() {
// This example uses Google's GSON
static final Gson GSON = new Gson();
@NonNull
@Override
public Optional<Object> marshalRequestBody(
@NonNull Request request,
@NonNull ResourceMethod resourceMethod,
@NonNull Parameter parameter,
@NonNull Type requestBodyType
) {
// Let GSON turn the request body into an instance
// of the specified type.
//
// Note that this method has access to all runtime information
// about the request, which provides the opportunity to, for example,
// examine annotations on the method/parameter which might
// inform custom marshaling strategies.
String body = request.getBodyAsString()
.filter(value -> !value.isBlank())
.orElseThrow(() -> new IllegalRequestBodyException(
"Request body must contain JSON."
));
try {
Object value = GSON.fromJson(body, requestBodyType);
if (value == null)
throw new IllegalRequestBodyException(
"Request body must contain a non-null JSON value."
);
return Optional.of(value);
} catch (JsonParseException e) {
// Expected parse failures are client errors. Keep request data and
// the parser's input-bearing cause out of the public diagnostic.
throw new IllegalRequestBodyException(
"Request body is not valid JSON."
);
}
}
}).build();
With the above marshaler configured, your Resource Methods can now accept JSON via statically-typed @RequestBody parameters. Any construct that Gson knows how to marshal is now available to your code.
@POST("/find-biggest")
public Integer findBiggest(@RequestBody List<Integer> numbers) {
// JSON request body [1,2,3] results in 3 being returned
return Collections.max(numbers);
}
@POST("/find-biggest")
public Integer findBiggest(@RequestBody List<Integer> numbers) {
// JSON request body [1,2,3] results in 3 being returned
return Collections.max(numbers);
}
# Send up request body of [1,2,3]
% curl -i -X POST 'http://localhost:8080/find-biggest' \
-H 'Content-Type: application/json' \
-d '[1,2,3]'
HTTP/1.1 200 OK
Content-Length: 1
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT
3
# Send up request body of [1,2,3]
% curl -i -X POST 'http://localhost:8080/find-biggest' \
-H 'Content-Type: application/json' \
-d '[1,2,3]'
HTTP/1.1 200 OK
Content-Length: 1
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT
3
Gson also handles POJOs and Record types, which are often used in POST, PUT, and PATCH operations.
public record Employee (
UUID id,
String name
) {}
// Accepts a JSON-formatted Record type as input
@POST("/employees")
public void createEmployee(@RequestBody Employee employee) {
System.out.printf("Create %s\n", employee.name());
}
public record Employee (
UUID id,
String name
) {}
// Accepts a JSON-formatted Record type as input
@POST("/employees")
public void createEmployee(@RequestBody Employee employee) {
System.out.printf("Create %s\n", employee.name());
}
# Send up request body of {"id": "...", "name": "..."}
% curl -i -X POST 'http://localhost:8080/employees' \
-H 'Content-Type: application/json' \
-d '{"id": "734ad459-0ebe-4c64-ba93-1dedf65d4ce2", "name": "Test"}'
HTTP/1.1 204 No Content
Date: Sun, 21 Mar 2024 16:19:01 GMT
# Send up request body of {"id": "...", "name": "..."}
% curl -i -X POST 'http://localhost:8080/employees' \
-H 'Content-Type: application/json' \
-d '{"id": "734ad459-0ebe-4c64-ba93-1dedf65d4ce2", "name": "Test"}'
HTTP/1.1 204 No Content
Date: Sun, 21 Mar 2024 16:19:01 GMT
Don't Need Custom Request Body Handling?
Not every system needs to "speak JSON". You might only require standard URL-Encoded and Multipart forms to consume input from your clients. Soklet has you covered in both cases.
- For working with
application/x-www-form-urlencodedrequests, see Form Parameters. - For working with
multipart/form-datarequests, see Multipart Form Data.
Default BigInteger, BigDecimal, and Number conversion accepts at most 4,096 trimmed characters. Decimal values additionally require absolute scale and adjusted exponent (precision - scale - 1) at most 4,096. Values outside these bounds fail normal binding with HTTP 400. Register a custom converter when a larger numeric domain is intentional. The first decoded Accept quality (q) value is limited to 16 characters; exceeding it makes that media range malformed.
Form Parameters
URL-encoded form bodies accept at most 1,000 nonempty name/value pairs, including repeated names. Exceeding this limit raises HTTP 400 when form parameters are accessed. Empty separator segments do not count toward the limit. Use UTF-8 for ordinary forms; see request text decoding for percent-encoding requirements with other charsets.
Soklet natively supports application/x-www-form-urlencoded request encoding, which is a method to transmit non-binary data (e.g. text inputs in an HTML <form>). Form parameter names are case-sensitive.
HTML Form
<form
enctype="application/x-www-form-urlencoded"
action="https://example.soklet.com/form?id=123"
method="POST"
>
<!-- User can type whatever text they like -->
<input type="number" name="numericValue" />
<!-- Multiple values for the same name are supported -->
<input type="hidden" name="multi" value="1" />
<input type="hidden" name="multi" value="2" />
<!-- Names with special characters can be remapped -->
<textarea name="long-text"></textarea>
<!-- Note: browsers send "on" string to indicate "checked" -->
<input type="checkbox" name="enabled" />
<input type="submit" />
</form>
<form
enctype="application/x-www-form-urlencoded"
action="https://example.soklet.com/form?id=123"
method="POST"
>
<!-- User can type whatever text they like -->
<input type="number" name="numericValue" />
<!-- Multiple values for the same name are supported -->
<input type="hidden" name="multi" value="1" />
<input type="hidden" name="multi" value="2" />
<!-- Names with special characters can be remapped -->
<textarea name="long-text"></textarea>
<!-- Note: browsers send "on" string to indicate "checked" -->
<input type="checkbox" name="enabled" />
<input type="submit" />
</form>
Resource Method
@POST("/form")
public MarshaledResponse form(
@QueryParameter Long id,
@FormParameter Integer numericValue,
@FormParameter(optional=true) List<String> multi,
@FormParameter(name="long-text") String longText,
@FormParameter String enabled
) {
// Echo back the inputs
return MarshaledResponse.withStatusCode(200)
.body(
List.of(id, numericValue, multi, longText, enabled).stream()
.map(Object::toString)
.collect(Collectors.joining("\n"))
.getBytes(StandardCharsets.UTF_8)
)
.build();
}
@POST("/form")
public MarshaledResponse form(
@QueryParameter Long id,
@FormParameter Integer numericValue,
@FormParameter(optional=true) List<String> multi,
@FormParameter(name="long-text") String longText,
@FormParameter String enabled
) {
// Echo back the inputs
return MarshaledResponse.withStatusCode(200)
.body(
List.of(id, numericValue, multi, longText, enabled).stream()
.map(Object::toString)
.collect(Collectors.joining("\n"))
.getBytes(StandardCharsets.UTF_8)
)
.build();
}
Test
% curl -i -X POST 'https://example.soklet.com/form?id=123' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'numericValue=456&multi=1&multi=2&long-text=long%20multiline%20text&enabled=on'
HTTP/1.1 200 OK
Content-Length: 37
Date: Sun, 21 Mar 2024 16:19:01 GMT
123
456
[1, 2]
long multiline text
on
% curl -i -X POST 'https://example.soklet.com/form?id=123' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'numericValue=456&multi=1&multi=2&long-text=long%20multiline%20text&enabled=on'
HTTP/1.1 200 OK
Content-Length: 37
Date: Sun, 21 Mar 2024 16:19:01 GMT
123
456
[1, 2]
long multiline text
on
Multipart Form Data
Soklet natively supports multipart/form-data request encoding, which is a method primarily used to transmit binary files but may include non-binary data as well (e.g. text inputs in an HTML <form>). The MultipartField type provides easy access to filename, content type, and field data in byte[] or String format. Multipart field names are case-sensitive.
The default parser preserves literal backslashes in quoted field names and filenames, including repeated or trailing backslashes and Windows drive/UNC paths. This matches the literal-backslash convention used by browser form serialization; backslashes are not treated as MIME escape characters.
MultipartField equality and hashing compare the name, filename, content type, explicitly configured charset and binary contents. Lazy string decoding does not affect equality. Equal repeated parts remain separate entries in the request's ordered lists; scalar access and binding still reject repeats. Null or empty data arrays represent an absent value. Backing bytes are shared without defensive copying: do not modify the input array after building a field or the array returned by getData(). Clone it for a mutable working copy.
Treat MultipartField.getFilename() as untrusted client input, not a safe filesystem path. It may contain path components or control characters. Generate a storage name yourself, keep writes under an application-controlled directory, and validate any separately retained display filename; never resolve this value directly against a storage root.
HTML Form
<form
enctype="multipart/form-data"
action="https://example.soklet.com/multipart?id=123"
method="POST"
>
<!-- User can type whatever text they like -->
<input type="text" name="freeform" />
<!-- Multiple values for the same name are supported -->
<input type="hidden" name="multi" value="1" />
<input type="hidden" name="multi" value="2" />
<!-- Prompt user to upload a file -->
<p>Please attach your document: <input name="doc" type="file" /></p>
<!-- Multiple file uploads are supported -->
<p>
Supplement 1: <input name="extra" type="file" /> Supplement 2:
<input name="extra" type="file" />
</p>
<!-- An optional file -->
<p>Optionally, attach a photo: <input name="photo" type="file" /></p>
<input type="submit" value="Upload" />
</form>
<form
enctype="multipart/form-data"
action="https://example.soklet.com/multipart?id=123"
method="POST"
>
<!-- User can type whatever text they like -->
<input type="text" name="freeform" />
<!-- Multiple values for the same name are supported -->
<input type="hidden" name="multi" value="1" />
<input type="hidden" name="multi" value="2" />
<!-- Prompt user to upload a file -->
<p>Please attach your document: <input name="doc" type="file" /></p>
<!-- Multiple file uploads are supported -->
<p>
Supplement 1: <input name="extra" type="file" /> Supplement 2:
<input name="extra" type="file" />
</p>
<!-- An optional file -->
<p>Optionally, attach a photo: <input name="photo" type="file" /></p>
<input type="submit" value="Upload" />
</form>
Resource Method
@POST("/multipart")
public Response multipart(
@QueryParameter Long id,
// Multipart fields work like other Soklet params
// with support for Optional<T>, List<T>, custom names, ...
@Multipart(optional=true) String freeform,
@Multipart(name="multi") List<Integer> numbers,
// The MultipartField type allows access to additional data,
// like filename and content type (if available).
// The @Multipart annotation is optional
// when your parameter is of type MultipartField...
@Multipart(name="doc") MultipartField document,
// ...but is useful if you need to massage the name.
@Multipart(name="extra") List<MultipartField> supplements,
// Keep filename metadata for an optional browser file input
@Multipart(optional=true) MultipartField photo
) {
// Let's demonstrate the functionality MultipartField provides.
// Form field name, always available, here "doc"
String name = document.getName();
// Browser may provide this for files, e.g. "test.pdf"
Optional<String> filename = document.getFilename();
// Browser may provide this for files, e.g. "application/pdf"
Optional<String> contentType = document.getContentType();
// Field data as bytes, if available
Optional<byte[]> data = document.getData();
// Keep binary uploads (such as PDF files) as bytes.
// Use getDataAsString() only for fields whose content is known to be text.
// Browsers may submit an empty part for an unselected file input.
// optional=true permits an absent part; it does not discard an empty one.
boolean photoSelected = photo != null && photo.getFilename().isPresent();
// Apply the standard redirect-after-POST pattern
return Response.withRedirect(
RedirectType.HTTP_303_SEE_OTHER, "/thanks"
).build();
}
@POST("/multipart")
public Response multipart(
@QueryParameter Long id,
// Multipart fields work like other Soklet params
// with support for Optional<T>, List<T>, custom names, ...
@Multipart(optional=true) String freeform,
@Multipart(name="multi") List<Integer> numbers,
// The MultipartField type allows access to additional data,
// like filename and content type (if available).
// The @Multipart annotation is optional
// when your parameter is of type MultipartField...
@Multipart(name="doc") MultipartField document,
// ...but is useful if you need to massage the name.
@Multipart(name="extra") List<MultipartField> supplements,
// Keep filename metadata for an optional browser file input
@Multipart(optional=true) MultipartField photo
) {
// Let's demonstrate the functionality MultipartField provides.
// Form field name, always available, here "doc"
String name = document.getName();
// Browser may provide this for files, e.g. "test.pdf"
Optional<String> filename = document.getFilename();
// Browser may provide this for files, e.g. "application/pdf"
Optional<String> contentType = document.getContentType();
// Field data as bytes, if available
Optional<byte[]> data = document.getData();
// Keep binary uploads (such as PDF files) as bytes.
// Use getDataAsString() only for fields whose content is known to be text.
// Browsers may submit an empty part for an unselected file input.
// optional=true permits an absent part; it does not discard an empty one.
boolean photoSelected = photo != null && photo.getFilename().isPresent();
// Apply the standard redirect-after-POST pattern
return Response.withRedirect(
RedirectType.HTTP_303_SEE_OTHER, "/thanks"
).build();
}
An unselected browser file input can still create a present MultipartField whose filename and data are empty. Check getFilename().isEmpty() when your form needs to distinguish that case; an intentionally selected zero-byte file may still have a filename. A required MultipartField binding checks for the part, not for a selected file. A byte[] or String binding receives only the part's data, so the filename distinction is lost, and it treats a part with no data as absent: an unselected file input or a zero-byte file returns 400 when the binding is required, and binds an empty Optional when it is optional.
Soklet provides its own multipart parsing support out-of-the-box. If you'd like to do it yourself, you may supply your own MultipartParser implementation. This is useful if you have specialized requirements or would like to simulate edge-case scenarios for integration tests.
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.withPort(8080).multipartParser(new MultipartParser() {
@NonNull
@Override
public Map<String, List<MultipartField>> extractMultipartFields(
@NonNull Request request
) {
// Inspect the request and return multipart fields
return Map.of();
}
}).build()
).build();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.withPort(8080).multipartParser(new MultipartParser() {
@NonNull
@Override
public Map<String, List<MultipartField>> extractMultipartFields(
@NonNull Request request
) {
// Inspect the request and return multipart fields
return Map.of();
}
}).build()
).build();
If you write a custom implementation, you can acquire a reference the default instance via MultipartParser::defaultInstance and delegate to it as needed.
Use Caution!
Soklet is designed to power systems that exchange small "transactional" payloads which live entirely in memory. It is not appropriate for handling multipart files at scale, buffering uploads to disk, streaming, etc.
Should you have these requirements, Soklet is better suited for providing clients with a cryptographically-signed upload URL for a third party storage service. Popular and scalable solutions include:
Conditional Requests
ConditionalRequests evaluates HTTP preconditions against application-supplied validators. Use responseFor(...) for the default bodyless 304/412 response, or evaluate(...) for an immutable ConditionalRequestResult that lets the application build its own response:
Proceedexposes the preconditions that were evaluated and true at the supplied snapshot.NotModifiedidentifies the cache condition that stopped a GET/HEAD request.PreconditionFailedidentifies the failed precondition and distinguishesCONDITION_FALSE,MALFORMED, andENTITY_TAG_LIST_LIMIT_EXCEEDED.
The three result types and Precondition are closed, so a switch over them needs no default branch. PreconditionFailed.Reason may gain constants in later 4.x releases; include a default branch when switching over it. Precondition.getHeaderName() returns the request header name, such as If-Match, for error messages and logs.
evaluate(request, entityTag, lastModified) and responseFor(...) assume a current representation exists, even if both validators are null. Null validators never mean a missing resource. For a missing representation on a creating endpoint, use evaluateWithoutRepresentation(request). This lets If-None-Match: * proceed when absent, while If-Match: * fails.
Check ordinary authorization, routing, and resource failures first. Preconditions do not override an otherwise applicable 401, 403, 404 for a non-creating endpoint, or 405. OPTIONS ignores conditional fields, including when the application returns a file response; generated OPTIONS handling remains separate. CONNECT and TRACE have the same HTTP rule but are not currently represented by Soklet's HttpMethod. With typed @RequestBody parameters, body unmarshaling occurs before the method runs, so an invalid body can fail before in-method evaluation. See RFC 9110 section 13.2.1.
The convenience wrapper maps Proceed to Optional.empty(), NotModified to a bodyless 304, and any PreconditionFailed to a bodyless 412. The application still owns successful responses, validator values, and cache headers:
// Example of a conditional GET
@GET("/accounts/{accountId}")
public Response getAccount(
@NonNull Request request,
@NonNull @PathParameter UUID accountId
) {
// Load an account given its ID
Account account = this.accountService.find(accountId)
.orElseThrow(ExampleNotFoundException::new);
// Construct an ETag using a version number stored on the account
EntityTag entityTag = EntityTag.fromStrongValue(
format("account-%d", account.version())
);
// Prep last-modified info + response cache headers
Instant lastModified = account.updatedAt();
Map<String, List<String>> cacheHeaders = Map.of(
"Cache-Control", List.of("private, max-age=60"),
"Vary", List.of("Accept-Language")
);
// Cache successful representations and validations, but not rejected preconditions.
return switch (ConditionalRequests.evaluate(request, entityTag, lastModified)) {
case ConditionalRequestResult.PreconditionFailed ignored -> {
Map<String, List<String>> failureHeaders = new LinkedHashMap<>(cacheHeaders);
failureHeaders.put("Cache-Control", List.of("no-store"));
yield Response.withStatusCode(412)
.headers(ConditionalRequests.validatorHeaders(entityTag, lastModified, failureHeaders))
.build();
}
case ConditionalRequestResult.NotModified ignored -> Response.withStatusCode(304)
.headers(ConditionalRequests.validatorHeaders(entityTag, lastModified, cacheHeaders))
.build();
case ConditionalRequestResult.Proceed ignored -> Response.withStatusCode(200)
.headers(ConditionalRequests.validatorHeaders(entityTag, lastModified, cacheHeaders))
.body(account)
.build();
};
}
// Example of a conditional GET
@GET("/accounts/{accountId}")
public Response getAccount(
@NonNull Request request,
@NonNull @PathParameter UUID accountId
) {
// Load an account given its ID
Account account = this.accountService.find(accountId)
.orElseThrow(ExampleNotFoundException::new);
// Construct an ETag using a version number stored on the account
EntityTag entityTag = EntityTag.fromStrongValue(
format("account-%d", account.version())
);
// Prep last-modified info + response cache headers
Instant lastModified = account.updatedAt();
Map<String, List<String>> cacheHeaders = Map.of(
"Cache-Control", List.of("private, max-age=60"),
"Vary", List.of("Accept-Language")
);
// Cache successful representations and validations, but not rejected preconditions.
return switch (ConditionalRequests.evaluate(request, entityTag, lastModified)) {
case ConditionalRequestResult.PreconditionFailed ignored -> {
Map<String, List<String>> failureHeaders = new LinkedHashMap<>(cacheHeaders);
failureHeaders.put("Cache-Control", List.of("no-store"));
yield Response.withStatusCode(412)
.headers(ConditionalRequests.validatorHeaders(entityTag, lastModified, failureHeaders))
.build();
}
case ConditionalRequestResult.NotModified ignored -> Response.withStatusCode(304)
.headers(ConditionalRequests.validatorHeaders(entityTag, lastModified, cacheHeaders))
.build();
case ConditionalRequestResult.Proceed ignored -> Response.withStatusCode(200)
.headers(ConditionalRequests.validatorHeaders(entityTag, lastModified, cacheHeaders))
.body(account)
.build();
};
}
The example uses evaluate(...) to give 412 responses Cache-Control: no-store, while retaining the representation's cache policy on 200 and 304. Extra headers passed to responseFor(...) are sent on both 304 and 412, so use evaluate(...) when those responses need different cache policies.
Evaluated conditions and parsing
Evaluation follows HTTP precedence: If-Match suppresses If-Unmodified-Since, and If-None-Match suppresses If-Modified-Since, even for empty or malformed tag fields. Stop at the first decisive condition; ignored and suppressed fields are not a validation report. Invalid dates or dates without a current modification time are ignored. Date comparisons use whole-second precision.
Entity-tag lists use strong comparison for If-Match and weak comparison for If-None-Match. A weak client tag is valid but cannot satisfy strong comparison; a weak current tag cannot satisfy any valid If-Match list. An existing representation without an ETag still satisfies If-Match: *; a valid list does not match the unavailable tag. Empty If-Match is valid but false, while empty If-None-Match is valid and true.
Repeated entity-tag field lines are combined as a list; quoted commas remain inside tags. The bounded splitter currently permits 256 list elements, counting empty elements. Splitting/counting happens before validating nonempty tags: crossing the limit stops immediately; otherwise an unclosed quote or invalid tag is malformed. Thus a bad tag plus an over-limit ordinary list reports the limit, while an early unclosed quote that absorbs later commas reports malformed syntax. A wildcard mixed into a list is malformed. On GET/HEAD, malformed or over-limit If-None-Match is ignored and suppresses date fallback; on other applicable methods it fails with the corresponding reason. Malformed or over-limit If-Match fails closed on any applicable method.
The Proceed set is immutable and describes only the evaluated snapshot:
| Member | What held | What it does not establish |
|---|---|---|
IF_MATCH | * found a representation, or a list matched its current strong tag | Which form was sent; * pins no revision |
IF_UNMODIFIED_SINCE | An available modification time was no later than a valid date, at whole-second precision | No write within that second |
IF_NONE_MATCH | No tag matched; empty lists and missing current tags can qualify | Revision-level lost-update protection or create-only intent |
IF_MODIFIED_SINCE | GET/HEAD's representation was modified since a valid date | A write guard |
A nonempty set does not certify safe lost-update protection, current authority, or continued truth at commit time. This optional application policy accepts an effective If-Match or If-Unmodified-Since and excludes ignored dates; it still permits If-Match: * and date precision limits:
private Response requireEffectiveWritePrecondition(
ConditionalRequestResult.Proceed proceed) {
Set<ConditionalRequestResult.Precondition> satisfied =
proceed.getSatisfiedPreconditions();
if (!satisfied.contains(ConditionalRequestResult.Precondition.IF_MATCH)
&& !satisfied.contains(ConditionalRequestResult.Precondition.IF_UNMODIFIED_SINCE))
return preconditionRequired();
return Response.fromStatusCode(204); // Guard passed; this does not perform a write.
}
private Response requireEffectiveWritePrecondition(
ConditionalRequestResult.Proceed proceed) {
Set<ConditionalRequestResult.Precondition> satisfied =
proceed.getSatisfiedPreconditions();
if (!satisfied.contains(ConditionalRequestResult.Precondition.IF_MATCH)
&& !satisfied.contains(ConditionalRequestResult.Precondition.IF_UNMODIFIED_SINCE))
return preconditionRequired();
return Response.fromStatusCode(204); // Guard passed; this does not perform a write.
}
Conditional writes and storage races
Evaluation does not lock storage. Use a fresh read, evaluate the client's conditions, then conditionally write the same version. If a known no-op CAS loses a race, reload and evaluate again. A wildcard or multi-tag condition can remain true after another write; an internal CAS failure alone is not a 412.
@PUT("/accounts/{accountId}")
public Response updateAccount(
@NonNull Request request,
@NonNull @PathParameter UUID accountId,
@NonNull @RequestBody UpdateAccountRequest update) {
// Normal authorization and semantic validation precede this example.
// Typed body unmarshaling has already happened before method entry.
for (int attempt = 0; attempt < 3; attempt++) {
Account current = this.accountService.find(accountId).orElse(null);
if (current == null)
return Response.fromStatusCode(404); // This endpoint does not create.
EntityTag tag = EntityTag.fromStrongValue("account-" + current.version());
switch (ConditionalRequests.evaluate(request, tag, current.updatedAt())) {
case ConditionalRequestResult.PreconditionFailed failed -> {
return Response.withStatusCode(412)
.headers(ConditionalRequests.validatorHeaders(tag, current.updatedAt()))
.body("Request precondition failed: "
+ failed.getPrecondition().getHeaderName()
+ " (" + failed.getReason().name() + ")")
.build();
}
case ConditionalRequestResult.NotModified ignored ->
throw new IllegalStateException("NotModified is unreachable for PUT");
case ConditionalRequestResult.Proceed ignored -> {
if (this.accountService.updateIfVersionMatches(
accountId, current.version(), update))
return Response.fromStatusCode(204);
// Known no-op: reload and evaluate the client's conditions again.
}
}
}
return Response.withStatusCode(409)
.body("Resource changed repeatedly; retry the request")
.build();
}
@PUT("/accounts/{accountId}")
public Response updateAccount(
@NonNull Request request,
@NonNull @PathParameter UUID accountId,
@NonNull @RequestBody UpdateAccountRequest update) {
// Normal authorization and semantic validation precede this example.
// Typed body unmarshaling has already happened before method entry.
for (int attempt = 0; attempt < 3; attempt++) {
Account current = this.accountService.find(accountId).orElse(null);
if (current == null)
return Response.fromStatusCode(404); // This endpoint does not create.
EntityTag tag = EntityTag.fromStrongValue("account-" + current.version());
switch (ConditionalRequests.evaluate(request, tag, current.updatedAt())) {
case ConditionalRequestResult.PreconditionFailed failed -> {
return Response.withStatusCode(412)
.headers(ConditionalRequests.validatorHeaders(tag, current.updatedAt()))
.body("Request precondition failed: "
+ failed.getPrecondition().getHeaderName()
+ " (" + failed.getReason().name() + ")")
.build();
}
case ConditionalRequestResult.NotModified ignored ->
throw new IllegalStateException("NotModified is unreachable for PUT");
case ConditionalRequestResult.Proceed ignored -> {
if (this.accountService.updateIfVersionMatches(
accountId, current.version(), update))
return Response.fromStatusCode(204);
// Known no-op: reload and evaluate the client's conditions again.
}
}
}
return Response.withStatusCode(409)
.body("Resource changed repeatedly; retry the request")
.build();
}
The application-owned service must make the version check and mutation atomic, never reuse versions, and return false only when it made no mutation. Every retry must see fresh committed state: do not loop inside an unchanged repeatable-read snapshot. Restart/recover transactions and serialization failures as required by the database. Failed attempts have no external effects; uncertain commits require application reconciliation rather than blind retries. A row lock across loading, evaluation, and writing is another valid strategy. The three-attempt limit and 409 are example policy, not Soklet defaults.
This example uses text error bodies supported by the default response marshaler. Structured JSON errors require an application response marshaler; returning a Map alone does not enable JSON serialization. A false If-Match or If-Unmodified-Since may receive success if the application establishes that the requested change is already applied. Do not execute the failed mutation again. This exception does not apply to false If-None-Match. Applications using durable receipts should resolve a known committed operation before treating its retry as a fresh mutation. See RFC 9110 section 13.1.
Creating a missing representation
An upsert must choose the insert or update branch on every fresh read. Use an atomic insert-if-absent and retry only the expected target-identity conflict, after rolling back any failed transaction. Do not retry unrelated constraint failures. A competing insert makes a create-only If-None-Match: * fail on reload:
@PUT("/documents/{documentId}")
public Response putDocument(
@NonNull Request request,
@NonNull @PathParameter UUID documentId,
@NonNull @RequestBody DocumentUpdate update) {
for (int attempt = 0; attempt < 3; attempt++) {
Document current = this.documentService.find(documentId).orElse(null);
if (current == null) {
if (ConditionalRequests.evaluateWithoutRepresentation(request)
instanceof ConditionalRequestResult.PreconditionFailed)
return Response.fromStatusCode(412);
if (this.documentService.insertIfAbsent(documentId, update))
return Response.fromStatusCode(201);
continue; // Known competing insert: reload and evaluate again.
}
EntityTag tag = EntityTag.fromStrongValue("document-" + current.version());
if (ConditionalRequests.evaluate(request, tag, current.updatedAt())
instanceof ConditionalRequestResult.PreconditionFailed)
return Response.withStatusCode(412)
.headers(ConditionalRequests.validatorHeaders(tag, current.updatedAt()))
.build();
if (this.documentService.updateIfVersionMatches(
documentId, current.version(), update))
return Response.fromStatusCode(204);
}
return Response.fromStatusCode(409);
}
@PUT("/documents/{documentId}")
public Response putDocument(
@NonNull Request request,
@NonNull @PathParameter UUID documentId,
@NonNull @RequestBody DocumentUpdate update) {
for (int attempt = 0; attempt < 3; attempt++) {
Document current = this.documentService.find(documentId).orElse(null);
if (current == null) {
if (ConditionalRequests.evaluateWithoutRepresentation(request)
instanceof ConditionalRequestResult.PreconditionFailed)
return Response.fromStatusCode(412);
if (this.documentService.insertIfAbsent(documentId, update))
return Response.fromStatusCode(201);
continue; // Known competing insert: reload and evaluate again.
}
EntityTag tag = EntityTag.fromStrongValue("document-" + current.version());
if (ConditionalRequests.evaluate(request, tag, current.updatedAt())
instanceof ConditionalRequestResult.PreconditionFailed)
return Response.withStatusCode(412)
.headers(ConditionalRequests.validatorHeaders(tag, current.updatedAt()))
.build();
if (this.documentService.updateIfVersionMatches(
documentId, current.version(), update))
return Response.fromStatusCode(204);
}
return Response.fromStatusCode(409);
}
The same known-no-effect, fresh-read, non-reused-version, and uncertain-commit rules apply. NotModified is unreachable for either PUT branch. A non-creating endpoint should return 404 before evaluation instead of using absent-resource evaluation.
Required-precondition policies
Soklet does not impose 428. Generic header presence checks should use public request.getHeaders(); getHeader(...) intentionally rejects repeated field lines. The following stricter application policy rejects legal general HTTP list/repeated forms deliberately, requires a concrete strong revision tag, and distinguishes missing 428, unsupported/malformed 400, and stale 412:
// Require one concrete strong tag before evaluating the write.
List<String> values = request.getHeaders().get("If-Match");
if (values == null || values.isEmpty())
return preconditionRequired(); // Application-owned 428, with no-store.
if (values.size() != 1)
return invalidPrecondition(); // Application-owned 400.
EntityTag expected = EntityTag.fromHeaderValue(values.get(0)).orElse(null);
if (expected == null || expected.isWeak())
return invalidPrecondition(); // Empty, malformed, *, list, or weak tag.
// evaluate(...) can now compare that one tag with the current representation.
// Require one concrete strong tag before evaluating the write.
List<String> values = request.getHeaders().get("If-Match");
if (values == null || values.isEmpty())
return preconditionRequired(); // Application-owned 428, with no-store.
if (values.size() != 1)
return invalidPrecondition(); // Application-owned 400.
EntityTag expected = EntityTag.fromHeaderValue(values.get(0)).orElse(null);
if (expected == null || expected.isWeak())
return invalidPrecondition(); // Empty, malformed, *, list, or weak tag.
// evaluate(...) can now compare that one tag with the current representation.
A strict create-only policy requires exactly one If-None-Match occurrence with the OWS-cleaned value * before absent-resource evaluation. The satisfied set alone cannot distinguish that wildcard from a valid nonmatching list. 428 responses must explain the required form and must not be cached. See RFC 6585 section 3.
Compression and strong validators
Automatic compression weakens a strong ETag on a compressed response. The same version may therefore yield a weak tag to a gzip client and a strong tag to an identity client, or retain a strong tag when the body is below the compression threshold. Weak validators work for If-None-Match; they cannot satisfy If-Match. Compression is disabled by default.
For cache validation when one semantic version covers both identity and compressed representations, use one consistent weak ETag. Supply that weak tag to both the normal response and ConditionalRequests. An encoded 200 automatically weakens a strong tag; a separately constructed bodyless 304 cannot reveal its omitted representation's compression eligibility. With compression enabled, Soklet preserves Vary: Accept-Encoding on 304 responses without invoking the compressor.
When clients must echo strong tags, the application can decline automatic compression for strong-tagged responses with today's compression hook:
private ResponseCompressor compressorPreservingStrongEtags() {
ResponseCompressor gzip =
ResponseCompressor.fromDefaultsWithMinimumBodySizeInBytes(1024);
ResponseCompressor compressor = (request, response) -> {
boolean strongTag = response.getHeaders().entrySet().stream()
.filter(entry -> entry.getKey().equalsIgnoreCase("ETag"))
.flatMap(entry -> entry.getValue().stream())
.map(EntityTag::fromHeaderValue)
.flatMap(Optional::stream)
.anyMatch(tag -> !tag.isWeak());
return strongTag ? ResponseCompressionPlan.none() : gzip.plan(request, response);
};
return compressor;
}
private ResponseCompressor compressorPreservingStrongEtags() {
ResponseCompressor gzip =
ResponseCompressor.fromDefaultsWithMinimumBodySizeInBytes(1024);
ResponseCompressor compressor = (request, response) -> {
boolean strongTag = response.getHeaders().entrySet().stream()
.filter(entry -> entry.getKey().equalsIgnoreCase("ETag"))
.flatMap(entry -> entry.getValue().stream())
.map(EntityTag::fromHeaderValue)
.flatMap(Optional::stream)
.anyMatch(tag -> !tag.isWeak());
return strongTag ? ResponseCompressionPlan.none() : gzip.plan(request, response);
};
return compressor;
}
Install the returned value with HttpServer.Builder.responseCompressor(...). This conservative recipe assumes valid application ETags and leaves the framework default unchanged. If identity is forbidden and the policy provides no acceptable coding, negotiation returns 406. Applications needing compressed strong-tagged variants must coordinate encoding and variant-specific validators before evaluation, including their bodyless 304 responses. Do not reinterpret weak If-Match tags as strong.
The simulator does not perform transport compression or transport-induced tag weakening. Explicit application weak tags remain weak there. Test this behavior over the real HTTP transport, including ETag, negotiated encoding, and 304 metadata; simulator-only tests cannot qualify it.
Applications own their validators. Soklet does not hash arbitrary response bodies or invent ETags. Hand-built 304 responses must preserve applicable ETag, Date, Vary, Cache-Control, Expires, and Content-Location metadata from the selected 200 representation. validatorHeaders(...) combines supplied metadata but cannot invent application cache policy. Standard HEAD body suppression still applies. File-backed responses retain their automatic GET/HEAD conditional and range handling; If-Range is outside ConditionalRequestResult.
HttpDate accepts HTTP's obsolete date forms and moving two-digit-year window, but rejects invalid dates and unserializable values. An unparseable conditional date is ignored rather than becoming a usable validator. See RFC 9110 section 15.4.5.
Effective Origin Resolution
Absolute request URLs supply the effective Host, replacing any supplied Host field. EffectiveOriginResolver.withRequest retains the URL scheme as a fallback; proxy headers are still subject to the selected trust policy. HTTP/1.1 requires one valid physical Host field even for an absolute request URL.
With TRUST_PROXY_ALLOWLIST, origin metadata comes from the nearest proxy: the rightmost Forwarded entry and the rightmost values of forwarded origin fields. Earlier entries cannot fill missing or invalid nearest values. TRUST_ALL retains leftmost selection. The trusted edge must strip or overwrite every forwarded header Soklet can read, including families that the edge itself does not generate. Soklet can fill missing scheme, host, or port fields from another family; trusting the socket peer does not authenticate client-supplied header values. See the complete header inventory and proxy examples.
Sometimes you need the client-facing origin (scheme + host + optional port) for logging or application URL handling. Soklet exposes EffectiveOriginResolver to derive an effective origin from request metadata while letting you decide whether to trust forwarded headers.
The effective origin is not a trusted application base URL. TRUST_NONE ignores forwarded headers, but an absolute-form request target can still supply both scheme and authority, even when its physical Host header names your application. allowOriginFallback(false) only disables the Origin header fallback; it does not disable this request-target information. Use a configured, trusted public base URL for password-reset links, verification links, and other security-sensitive URLs, and reject unrecognized public authorities at your edge or application boundary.
// Get a handle to a Request...
Request request = ...;
// ...and extract its effective origin using custom resolution rules.
Optional<String> effectiveOrigin = EffectiveOriginResolver
.withRequest(request, TrustPolicy.TRUST_PROXY_ALLOWLIST)
.trustedProxyAddresses(Set.of(
InetAddress.getByName("203.0.113.10")
))
.resolve();
// Get a handle to a Request...
Request request = ...;
// ...and extract its effective origin using custom resolution rules.
Optional<String> effectiveOrigin = EffectiveOriginResolver
.withRequest(request, TrustPolicy.TRUST_PROXY_ALLOWLIST)
.trustedProxyAddresses(Set.of(
InetAddress.getByName("203.0.113.10")
))
.resolve();
Forwarded headers are only used when permitted by the trust policy. If you cannot trust forwarded headers (e.g. Soklet is directly reachable, no load balancer/proxy in front), use TrustPolicy.TRUST_NONE instead. An ordinary request then has no source for the scheme, so resolve() returns Optional.empty() unless the request target is absolute-form, or Origin fallback is enabled and the request's Origin host matches Host. Trusted Forwarded host= and X-Forwarded-Host values are validated against the same strict host grammar as Host; invalid forwarded host values are ignored. Origin is treated as a fallback signal only (never overrides host). You can also control whether Origin fallback is enabled via EffectiveOriginResolver::allowOriginFallback—if left unset, it is enabled only for TrustPolicy.TRUST_ALL.
Example: Trusted Proxy Allowlist
Input
Remote Address:
203.0.113.10
Headers:
X-Forwarded-Proto: https
X-Forwarded-Host: api.example.com
Host: internal.soklet.local
Trust Policy:
TRUST_PROXY_ALLOWLIST
Trusted Proxy Addresses:
203.0.113.10
Remote Address:
203.0.113.10
Headers:
X-Forwarded-Proto: https
X-Forwarded-Host: api.example.com
Host: internal.soklet.local
Trust Policy:
TRUST_PROXY_ALLOWLIST
Trusted Proxy Addresses:
203.0.113.10
Output
https://api.example.com
https://api.example.com
Example: Untrusted Proxy With Origin Fallback
Input
Remote Address:
198.51.100.20
Headers:
Host: api.example.com
X-Forwarded-Proto: https
X-Forwarded-Host: evil.example.net
Origin: https://api.example.com
Trust Policy:
TRUST_PROXY_ALLOWLIST
Trusted Proxy Addresses:
12.34.100.20
Allow Origin Fallback:
true
Remote Address:
198.51.100.20
Headers:
Host: api.example.com
X-Forwarded-Proto: https
X-Forwarded-Host: evil.example.net
Origin: https://api.example.com
Trust Policy:
TRUST_PROXY_ALLOWLIST
Trusted Proxy Addresses:
12.34.100.20
Allow Origin Fallback:
true
Output
https://api.example.com
https://api.example.com
Example: Forwarded Header (Trust All)
Input
Headers:
Forwarded: proto=https;host=example.com:8443
Trust Policy:
TRUST_ALL
Headers:
Forwarded: proto=https;host=example.com:8443
Trust Policy:
TRUST_ALL
Output
https://example.com:8443
https://example.com:8443
References:
Effective Client IP Resolution
Request::getRemoteAddress exposes the raw socket peer. In production that is often your load balancer, ingress, or reverse proxy rather than the original client. Use EffectiveClientIpResolver when application code needs the client-facing IP address from trusted Forwarded: for= or X-Forwarded-For headers.
// Get a handle to a Request...
Request request = ...;
// ...and extract its effective client IP using custom resolution rules.
Optional<InetAddress> effectiveClientIp = EffectiveClientIpResolver
.withRequest(request, TrustPolicy.TRUST_PROXY_ALLOWLIST)
.trustedProxyAddresses(Set.of(
InetAddress.getByName("203.0.113.10")
))
.resolve();
// Get a handle to a Request...
Request request = ...;
// ...and extract its effective client IP using custom resolution rules.
Optional<InetAddress> effectiveClientIp = EffectiveClientIpResolver
.withRequest(request, TrustPolicy.TRUST_PROXY_ALLOWLIST)
.trustedProxyAddresses(Set.of(
InetAddress.getByName("203.0.113.10")
))
.resolve();
Forwarded client IP headers are only used when permitted by the trust policy. For TrustPolicy.TRUST_PROXY_ALLOWLIST, Soklet first verifies that the socket peer is trusted, then applies the same trust predicate while walking the forwarded IP chain from right to left and returns the first untrusted address. The allowlist must therefore contain every possible physical socket peer and every trusted proxy-hop address expected in the chain, never end-client addresses. This is the usual model for a trusted proxy appending its own address to a possibly client-controlled chain. If every forwarded address is trusted, the leftmost address is returned. If forwarded headers are unavailable or untrusted, the raw socket peer is returned when available. The trusted proxy or network edge must strip or overwrite both Forwarded and X-Forwarded-For; usable Forwarded: for= values take precedence over X-Forwarded-For.
Only IP literals are accepted from forwarded client-IP headers, so resolving an effective client IP never performs DNS lookups. Under TRUST_PROXY_ALLOWLIST, a hostname, unknown, obfuscated identifier, malformed value or invalid port stops the trusted-chain walk and falls back to the socket peer. Trusted proxies must emit IP literals. TRUST_ALL skips unusable entries instead.
Example: Trusted Proxy Allowlist
Input
Remote Address:
203.0.113.10
Headers:
X-Forwarded-For: 198.51.100.77, 203.0.113.10
Trust Policy:
TRUST_PROXY_ALLOWLIST
Trusted Proxy Addresses:
203.0.113.10
Remote Address:
203.0.113.10
Headers:
X-Forwarded-For: 198.51.100.77, 203.0.113.10
Trust Policy:
TRUST_PROXY_ALLOWLIST
Trusted Proxy Addresses:
203.0.113.10
Output
198.51.100.77
198.51.100.77
Example: Spoofed Forwarded Chain
Input
Remote Address:
10.0.0.3
Headers:
X-Forwarded-For: 198.51.100.10, 203.0.113.99, 10.0.0.2
Trust Policy:
TRUST_PROXY_ALLOWLIST
Trusted Proxy Addresses:
10.0.0.2
10.0.0.3
Remote Address:
10.0.0.3
Headers:
X-Forwarded-For: 198.51.100.10, 203.0.113.99, 10.0.0.2
Trust Policy:
TRUST_PROXY_ALLOWLIST
Trusted Proxy Addresses:
10.0.0.2
10.0.0.3
Output
203.0.113.99
203.0.113.99
References:
Trace Context
Soklet parses W3C traceparent and tracestate headers into Request::getTraceContext. This gives application code a typed way to correlate logs, spans, and outbound calls without adding ambient request context or thread-local propagation.
@GET("/checkout")
public String checkout(@NonNull Request request) {
request.getTraceContext().ifPresent(traceContext ->
logger.info("traceId={}", traceContext.getTraceId()));
return "ok";
}
@GET("/checkout")
public String checkout(@NonNull Request request) {
request.getTraceContext().ifPresent(traceContext ->
logger.info("traceId={}", traceContext.getTraceId()));
return "ok";
}
Malformed trace headers do not reject the request. Soklet simply exposes Optional::empty from getTraceContext().
For outbound propagation, write the normalized header values with your own HTTP client:
request.getTraceContext().ifPresent(traceContext -> {
outboundRequest.header("traceparent",
traceContext.toTraceparentHeaderValue());
traceContext.toTracestateHeaderValue().ifPresent(value ->
outboundRequest.header("tracestate", value));
});
request.getTraceContext().ifPresent(traceContext -> {
outboundRequest.header("traceparent",
traceContext.toTraceparentHeaderValue());
traceContext.toTracestateHeaderValue().ifPresent(value ->
outboundRequest.header("tracestate", value));
});
Use TraceContext::getTraceStateEntries when you need validated W3C tracestate entries. Use TraceContext::toTracestateHeaderValue when you only need to propagate the serialized header value.
Soklet Types
For easy access, Soklet will inject your Resource Method's Java method parameters with instances that correspond to values pulled from your current SokletConfig. The name of each parameter is arbitrary; matching is done by type.
@GET("/soklet-types")
public void sokletTypes(
// A handle to the current Resource Method (this one!)
ResourceMethod resourceMethod,
// Your configured SSE server
SseServer sseServer,
// Your other configured types
InstanceProvider instanceProvider,
RequestBodyMarshaler requestBodyMarshaler,
ValueConverterRegistry valueConverterRegistry,
ResourceMethodResolver resourceMethodResolver,
RequestInterceptor requestInterceptor,
LifecycleObserver lifecycleObserver,
CorsAuthorizer corsAuthorizer,
ResourceMethodParameterProvider resourceMethodParameterProvider
) {
// Let's use the SseServer reference to broadcast an event:
ResourcePath resourcePath =
ResourcePath.fromPath("/chats/123/event-source");
// Build the event...
SseEvent event = SseEvent.withEvent("chat-message")
.data("Hello, world")
.build();
// ...and broadcast it to SSE clients
sseServer.acquireBroadcaster(resourcePath)
.ifPresent(broadcaster -> broadcaster.broadcastEvent(event));
}
@GET("/soklet-types")
public void sokletTypes(
// A handle to the current Resource Method (this one!)
ResourceMethod resourceMethod,
// Your configured SSE server
SseServer sseServer,
// Your other configured types
InstanceProvider instanceProvider,
RequestBodyMarshaler requestBodyMarshaler,
ValueConverterRegistry valueConverterRegistry,
ResourceMethodResolver resourceMethodResolver,
RequestInterceptor requestInterceptor,
LifecycleObserver lifecycleObserver,
CorsAuthorizer corsAuthorizer,
ResourceMethodParameterProvider resourceMethodParameterProvider
) {
// Let's use the SseServer reference to broadcast an event:
ResourcePath resourcePath =
ResourcePath.fromPath("/chats/123/event-source");
// Build the event...
SseEvent event = SseEvent.withEvent("chat-message")
.data("Hello, world")
.build();
// ...and broadcast it to SSE clients
sseServer.acquireBroadcaster(resourcePath)
.ifPresent(broadcaster -> broadcaster.broadcastEvent(event));
}
Other Parameters
If Soklet does not know how to inject a Resource Method parameter, it will ask your InstanceProvider for an instance of one (see Instance Creation for details on how to configure it). A Dependency Injection library like Google Guice can be particularly helpful here.
With the default providers, startup warns about unannotated value parameters that may have been intended to bind request data, such as String, enums, and JDK collection or map types. This warning does not change injection or reject startup. See Specifying an Instance Provider for its scope.
For example, suppose you have a MyBackend that's required to do some work. Just declare it as a Resource Method parameter and Soklet will take care of injecting it.
// Request body
public record AuthRequest (
String emailAddress,
String password
) {}
// Response body
public record AuthResponse (
String jwt
) {}
// Example backend
public static class MyBackend {
public String acquireJwt(AuthRequest authReq) {
// Error handling elided...
// ...and this is not a real JWT :)
return String.format("%s-JWT", authReq.emailAddress());
}
}
@POST("/example-auth")
public AuthResponse exampleAuth(
@RequestBody AuthRequest authReq,
MyBackend myBackend // vended by your InstanceProvider
) {
// Ask MyBackend for a JWT to carry credentials
String jwt = myBackend.acquireJwt(authReq);
return new AuthResponse(jwt);
}
// Request body
public record AuthRequest (
String emailAddress,
String password
) {}
// Response body
public record AuthResponse (
String jwt
) {}
// Example backend
public static class MyBackend {
public String acquireJwt(AuthRequest authReq) {
// Error handling elided...
// ...and this is not a real JWT :)
return String.format("%s-JWT", authReq.emailAddress());
}
}
@POST("/example-auth")
public AuthResponse exampleAuth(
@RequestBody AuthRequest authReq,
MyBackend myBackend // vended by your InstanceProvider
) {
// Ask MyBackend for a JWT to carry credentials
String jwt = myBackend.acquireJwt(authReq);
return new AuthResponse(jwt);
}
Copying Requests
If you need to adjust a Request (e.g. when rewriting it during request wrapping), use Request::copy to obtain a mutable copier, change the fields you need, then call Request.Copier::finish to build the new instance.
This "copy-to-change" workflow is necessary because Request objects are effectively immutable.
// Prefix the request's path with "/v2", e.g. to aid API versioning
Request updatedRequest = request.copy()
.path(format("/v2%s", request.getPath()))
// Convenience method to get a mutable copy of
// existing headers which you can modify in-place
.headers((Map<String, List<String>> mutableHeaders) -> {
mutableHeaders.put("X-Another-Header", List.of("example"));
})
.finish();
// Prefix the request's path with "/v2", e.g. to aid API versioning
Request updatedRequest = request.copy()
.path(format("/v2%s", request.getPath()))
// Convenience method to get a mutable copy of
// existing headers which you can modify in-place
.headers((Map<String, List<String>> mutableHeaders) -> {
mutableHeaders.put("X-Another-Header", List.of("example"));
})
.finish();
The copy is shallow for performance (for example, the request body byte array is reused), so treat the original as immutable.
Experts Only
Heads Up!
You will not normally need to customize Resource Method resolution and parameter injection. However, hooks are available to support unique use-cases.
Resource Method Resolution
The ResourceMethodResolver determines how to map HTTP requests to Resource Methods.
At compile time, SokletProcessor examines annotations like @GET, validates declarations and writes a route index. At runtime, the default resolver loads that index and resolves its declarations into cached Java Method objects. Soklet matches requests against its route index and invokes ordinary HTTP/SSE handlers reflectively. The explicit fromClasses(...) and fromMethods(...) factories inspect the supplied classes or methods at runtime. Automatic fromClasses(...) discovery ignores compiler bridge methods, so generic and covariant annotated handlers match index discovery without false duplicate routes. fromMethods(...) preserves the caller's explicit method selection.
Declare annotated routes directly on the public concrete resource class you register. Inherited annotated methods, interface default methods and visibility bridges are not a supported way to select a subclass receiver or preserve generic binding metadata in 4.0.0.
Ensure Soklet's Annotation Processor Runs
If a startup failure includes this message (the first sentence is shown):
No Soklet Resource Methods were found.
For default classpath discovery, ensure Soklet's SokletProcessor runs when compiling your application's annotated Resource Methods:
- Gradle: declare
com.soklet:soklet:4.0.0on bothimplementationandannotationProcessor. - Maven: include Soklet in the compiler plugin's
annotationProcessorPathsand selectcom.soklet.SokletProcessorinannotationProcessorswhen processors are explicitly enumerated. Keep any other required processors in both relevant lists. - Direct
javac: use-processor com.soklet.SokletProcessorwith Soklet on the compiler classpath or processor path. - In every build, enable
-parameters(for Maven,<parameters>true</parameters>; for Gradle, add-parameterstoJavaCompile.options.compilerArgs).
Preserve the generated META-INF/soklet/resource-method-lookup-table resource when packaging or shading the application. Compilation alone does not prove the index survived: inspect the final application JAR and test its packaged HTTP/SSE routes. If combining multiple route-bearing JARs into one shaded JAR, preserve all lookup-table entries rather than overwriting one with another. Use an AppendingTransformer for each Soklet index with Maven Shade:
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/soklet/resource-method-lookup-table</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/soklet/mcp-endpoint-descriptor-providers</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/soklet/resource-method-lookup-table</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/soklet/mcp-endpoint-descriptor-providers</resource>
</transformer>
For Gradle Shadow, append both indexes:
tasks.named('shadowJar') {
append 'META-INF/soklet/resource-method-lookup-table'
append 'META-INF/soklet/mcp-endpoint-descriptor-providers'
}
tasks.named('shadowJar') {
append 'META-INF/soklet/resource-method-lookup-table'
append 'META-INF/soklet/mcp-endpoint-descriptor-providers'
}
During incremental HTTP/SSE compilation, the processor merges new declarations into one prior snapshot. Current compiler output takes precedence over the enabled sidecar and persistent caches, including an empty current index. Retained owners must still resolve from the compiler's source path or classpath; keep untouched application types and dependency JARs visible there. The same visibility and clean-build rules apply to annotated MCP endpoint owners. For direct javac, always select an output directory with -d. When recompiling only some sources, also include that directory on the compiler's -cp along with Soklet and your dependencies: -d alone does not make prior classfiles visible. Otherwise an apparently successful partial compile can remove untouched owners from the generated index. If that happens, clean and recompile all annotated sources before packaging. Preserve the generated META-INF/soklet resources beside the classfiles in the runtime artifact. Package only successful compiler output: late javac or cache-publication errors can leave partial generated indexes, so recover from those failures with a clean build.
After deleting, renaming, or moving a resource owner into a dependency, perform a normal mvn clean or gradle clean before recompiling all annotated code. Removing only the classes directory is insufficient: the default sidecar lives outside it and can restore old rows when the owner still resolves from a dependency. With custom persistent caching, remove that cache as well. An old classfile visible to the compiler remains a usable type. If compilation reports an unreadable or malformed generated route index, delete the index at the reported location and rebuild all annotated code. The processor preserves the selected snapshot on a read failure. A cache update failure invalidates the stale cache; failure to update or invalidate it is also reported as a compilation error.
If you configured a custom ResourceMethodResolver, its getResourceMethods() must return the configured HTTP/SSE Resource Methods. A custom resolver that returns no routes is a different cause from missing generated metadata.
However, you might need custom behavior to handle special cases. For example, suppose you have public-facing URLs that are frequently mistyped and you'd like to perform fuzzy matching on URL paths to resolve them so long as they are "close enough". Or suppose you have many equivalent URLs that map to the same method - in a way not easily solvable with path parameters - and it's awkward to manually "stack" dozens of @GET annotations on the same method.
Having runtime access to route resolution grants expressive abilities not otherwise achievable by compile-time configuration.
Example Implementation
First, let's make a method we can use to handle HTTP requests. Because we are making a custom ResourceMethodResolver, the method itself does not need a @GET (or similar) annotation.
public class ExampleResource {
// No annotations here
public String hardcodedHandler() {
return "this is hardcoded";
}
}
public class ExampleResource {
// No annotations here
public String hardcodedHandler() {
return "this is hardcoded";
}
}
Now that the class with our resource-handling method is defined, we can configure Soklet with a custom ResourceMethodResolver that routes requests directly to the method, ignoring Soklet's default resolution strategy.
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).resourceMethodResolver(new ResourceMethodResolver() {
private final Set<ResourceMethod> resourceMethods = createResourceMethods();
private Set<ResourceMethod> createResourceMethods() {
try {
Method method = ExampleResource.class.getMethod("hardcodedHandler");
ResourcePathDeclaration path = ResourcePathDeclaration.fromPath("/{path*}");
Set<ResourceMethod> methods = new HashSet<>();
for (HttpMethod httpMethod : HttpMethod.values())
methods.add(ResourceMethod.fromComponents(httpMethod, path, method, false));
return Set.copyOf(methods);
} catch (NoSuchMethodException exception) {
throw new IllegalStateException(exception);
}
}
@NonNull
@Override
public Set<ResourceMethod> getResourceMethods() {
// Startup needs the complete, finite inventory, including custom routes.
return resourceMethods;
}
@NonNull
@Override
public Optional<ResourceMethod> resourceMethodForRequest(
@NonNull Request request,
@NonNull ServerType serverType
) {
// If the request was for /hardcoded-404,
// return empty (i.e. no method matches this route)
if (request.getPath().equals("/hardcoded-404"))
return Optional.empty();
// Reuse registered catch-all declarations instead of creating one route
// per incoming URL (which would also create unbounded metric labels).
return resourceMethods.stream()
.filter(method -> method.getHttpMethod() == request.getHttpMethod())
.findFirst();
}
}).build();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).resourceMethodResolver(new ResourceMethodResolver() {
private final Set<ResourceMethod> resourceMethods = createResourceMethods();
private Set<ResourceMethod> createResourceMethods() {
try {
Method method = ExampleResource.class.getMethod("hardcodedHandler");
ResourcePathDeclaration path = ResourcePathDeclaration.fromPath("/{path*}");
Set<ResourceMethod> methods = new HashSet<>();
for (HttpMethod httpMethod : HttpMethod.values())
methods.add(ResourceMethod.fromComponents(httpMethod, path, method, false));
return Set.copyOf(methods);
} catch (NoSuchMethodException exception) {
throw new IllegalStateException(exception);
}
}
@NonNull
@Override
public Set<ResourceMethod> getResourceMethods() {
// Startup needs the complete, finite inventory, including custom routes.
return resourceMethods;
}
@NonNull
@Override
public Optional<ResourceMethod> resourceMethodForRequest(
@NonNull Request request,
@NonNull ServerType serverType
) {
// If the request was for /hardcoded-404,
// return empty (i.e. no method matches this route)
if (request.getPath().equals("/hardcoded-404"))
return Optional.empty();
// Reuse registered catch-all declarations instead of creating one route
// per incoming URL (which would also create unbounded metric labels).
return resourceMethods.stream()
.filter(method -> method.getHttpMethod() == request.getHttpMethod())
.findFirst();
}
}).build();
All /hardcoded-404 requests, regardless of HTTP method, are set up to have no matching route:
% curl -i 'http://localhost:8080/hardcoded-404'
HTTP/1.1 404 Not Found
Content-Length: 19
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT
HTTP 404: Not Found
% curl -i 'http://localhost:8080/hardcoded-404'
HTTP/1.1 404 Not Found
Content-Length: 19
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT
HTTP 404: Not Found
Any other request will be routed to the hardcoded handler:
% curl -i 'http://localhost:8080/could/be/anything?test=123'
HTTP/1.1 200 OK
Content-Length: 17
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT
this is hardcoded
% curl -i 'http://localhost:8080/could/be/anything?test=123'
HTTP/1.1 200 OK
Content-Length: 17
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT
this is hardcoded
If you're writing a custom ResourceMethodResolver, it's often useful to get a reference to Soklet's default implementation - for example, you might want custom resolution for a subset of URLs and fall back to standard behavior otherwise:
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).resourceMethodResolver(new ResourceMethodResolver() {
private final ResourceMethodResolver defaultResolver =
ResourceMethodResolver.fromClasspathIntrospection();
@Override
public Set<ResourceMethod> getResourceMethods() {
return defaultResolver.getResourceMethods();
}
@Override
public Optional<ResourceMethod> resourceMethodForRequest(
Request request,
ServerType serverType
) {
// Exclude this prefix; other requests use the configured default routes.
if (request.getPath().startsWith("/some/special/prefix/")) {
return Optional.empty();
}
return defaultResolver.resourceMethodForRequest(request, serverType);
}
}).build();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).resourceMethodResolver(new ResourceMethodResolver() {
private final ResourceMethodResolver defaultResolver =
ResourceMethodResolver.fromClasspathIntrospection();
@Override
public Set<ResourceMethod> getResourceMethods() {
return defaultResolver.getResourceMethods();
}
@Override
public Optional<ResourceMethod> resourceMethodForRequest(
Request request,
ServerType serverType
) {
// Exclude this prefix; other requests use the configured default routes.
if (request.getPath().startsWith("/some/special/prefix/")) {
return Optional.empty();
}
return defaultResolver.resourceMethodForRequest(request, serverType);
}
}).build();
References
ResourceMethodResolverResourceMethodResolver::fromClasspathIntrospectionResourceMethodResolver::fromClassesResourceMethodResolver::fromMethodsServerType
Resource Method Parameter Injection
The ResourceMethodParameterProvider determines how to inject appropriate parameter values when invoking Resource Methods.
// This is the contract - given a request and Resource Method,
// supply the parameters to be passed to the Resource Method when invoked
@FunctionalInterface
public interface ResourceMethodParameterProvider {
@NonNull
List<Object> parameterValuesForResourceMethod(
@NonNull Request request,
@NonNull ResourceMethod resourceMethod
);
}
// This is the contract - given a request and Resource Method,
// supply the parameters to be passed to the Resource Method when invoked
@FunctionalInterface
public interface ResourceMethodParameterProvider {
@NonNull
List<Object> parameterValuesForResourceMethod(
@NonNull Request request,
@NonNull ResourceMethod resourceMethod
);
}
Soklet's default implementation uses reflection to examine Resource Method parameter types and annotations and pulls the corresponding values out of the request and applies any needed Value Conversions. If Soklet does not know how to provide a parameter (for example, an un-annotated MyCustomType) Soklet will ask your InstanceProvider for an instance of one.
For example, a Resource Method parameter declared as @RequestBody LocalDate date would trigger the default parameter provider to attempt to convert the request body data to an instance of LocalDate, throwing a MissingRequestBodyException if no request body is available or IllegalRequestBodyException if the request body is malformed.
You can wire in your ResourceMethodParameterProvider like this:
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).resourceMethodParameterProvider(new ResourceMethodParameterProvider() {
@NonNull
@Override
public List<Object> parameterValuesForResourceMethod(
@NonNull Request request,
@NonNull ResourceMethod resourceMethod
) {
// Your parameter-value-providing code goes here
}
}).build();
SokletConfig config = SokletConfig.withHttpServer(
HttpServer.fromPort(8080)
).resourceMethodParameterProvider(new ResourceMethodParameterProvider() {
@NonNull
@Override
public List<Object> parameterValuesForResourceMethod(
@NonNull Request request,
@NonNull ResourceMethod resourceMethod
) {
// Your parameter-value-providing code goes here
}
}).build();
Heads Up!
It's unusual to provide your own implementation of ResourceMethodParameterProvider.
You can generally achieve the behavior you're looking for providing a custom InstanceProvider - for example, you might want to provide different flavors of MyCustomInstance based on how the parameter is annotated (solving the "robot legs" problem). See Instance Creation for details.

