Path Contexts

To serve requests from a sub-path, add a context handler using the ContextHandlerBuilderclass, and then add handlers to that context.

The request object can provide the full path, or the context path, or path relative to the context.

Contexts can also be nested.

The following example exposes 3 paths:

public class ContextsExample {
    public static void main(String[] args) {
        MuServer server = MuServerBuilder.httpServer()
            .addHandler(Method.GET, "/something", (request, response, pathParams) -> {
                sendInfo(request, response, "No context");
            })
            .addHandler(
                ContextHandlerBuilder.context("api")
                    .addHandler(Method.GET, "/something", (request, response, pathParams) -> {
                        sendInfo(request, response, "First level context");
                    })
                    .addHandler(
                        ContextHandlerBuilder.context("nested")
                            .addHandler(Method.GET, "/something", (request, response, pathParams) -> {
                                sendInfo(request, response, "Nested context");
                            })
                    )
            )
            .start();
        System.out.println("Started server at " + server.uri().resolve("/something"));
    }

    private static void sendInfo(MuRequest request, MuResponse response, String description) {
        response.contentType("text/html");
        response.write(description + "<br>" +
            "Full path: " + request.uri().getPath() + "<br>" +
            "Context path: " + request.contextPath() + "<br>" +
            "Relative path: " + request.relativePath()
        );
    }
}
(see full file)

The corresponding requests have the following values:

Full path Context path Relative path
/something / /something
/api/something /api /something
/api/nested/something /api/nested /something

One common case for contexts is hosting static data on a sub-path. To do that, just add a resource handler to a context. The example hosts static data at /static:

public class ResourceHandlingWithContext {
    public static void main(String[] args) {
        MuServer server = MuServerBuilder.httpServer()
            .addHandler(context("static")
                .addHandler(ResourceHandlerBuilder.classpathHandler("/web"))
            )
            .start();
        System.out.println("Stylesheet available at "
            + server.uri().resolve("/static/mu.css"));
    }
}
(see full file)