avaje-jex 3.0-RC24 API
Avaje Jex
Avaje Jex is a wrapper over the JDK's built-in HTTP server, providing an elegant and developer-friendly API for building web applications in Java.
Getting Started
Here's a simple example to create a basic web server with Jex:
Jex.create()
.get("/", ctx -> ctx.text("hello"))
.get("/one/{id}", ctx -> ctx.text("one-" + ctx.pathParam("id")))
.filter(
(ctx, chain) -> {
System.out.println("before request");
chain.proceed();
System.out.println("after request");
})
.error(
IllegalStateException.class,
(ctx, exception) -> ctx.status(500).text(exception.getMessage()))
.port(8080)
.start();
Key Concepts
Request Handling
Jex provides three main handler types:
- Endpoint Handlers - Define API endpoints for HTTP methods (GET, POST, etc.)
- Filters - Pre/post process requests for authentication, logging, etc.
- Exception Handlers - Handle exceptions during request processing
Context Object
The Context object is central to Jex's API, providing methods for:
- Reading request data (headers, parameters, body)
- Setting response data (status, headers, content)
- Managing cookies
- Handling request attributes and path information
Path Parameters
Jex supports flexible path parameter options:
// Standard path parameters with {} syntax
app.get("/hello/{name}", ctx -> ctx.write("Hello: " + ctx.pathParam("name")));
// Path parameters that can include slashes with <> syntax
app.get("/hello/<name>", ctx -> ctx.write("Hello: " + ctx.pathParam("name")));
// Wildcard parameters
app.get("/path/*", ctx -> ctx.write("Matched: " + ctx.matchedPath()));
Advanced Features
JSON Support
Jex provides a JsonService SPI for JSON serialization/deserialization, with automatic
detection of Jackson or Avaje-jsonb libraries:
Jex.create()
.jsonService(new JacksonJsonService())
.post(
"/json",
ctx -> {
MyBody body = ctx.bodyAsClass(MyBody.class);
ctx.json(new CustomResponse());
});
Server-Sent Events
Jex supports Server-Sent Events (SSE) for real-time updates:
app.sse("/sse", client -> {
client.sendEvent("connected", "Hello, SSE");
client.onClose(() -> System.out.println("Client disconnected"));
});
Access Management
Jex provides built-in support for role-based access control:
// Custom enum for access roles
enum Access implements Role {
USER,
ADMIN
}
Jex.create()
.get("/user", ctx -> ctx.text("user"), Access.USER)
.get("/admin", ctx -> ctx.text("admin"), Access.ADMIN)
.filter(
(ctx, chain) -> {
Access userRole = getUserRole(ctx);
if (!ctx.routeRoles().contains(userRole)) {
throw new HttpResponseException(403, "unauthorized");
}
chain.proceed();
});
Additional Resources
For more informationm visit: