Path and query parameters
A client often passes data right in the address. A path parameter is part of the address itself: in /posts/5 the number 5 is the post number. A query parameter is a name=value pair after the question mark: /search?q=java&limit=5. Javalin gives access to both through ctx.
A path parameter
In a route the parameter is written in curly braces and read with the ctx.pathParam method:
// src/main/java/com/example/blog/Main.java
config.routes.get("/posts/{id}", ctx -> {
String id = ctx.pathParam("id");
ctx.result("Post #" + id);
});curl http://localhost:8080/posts/5Post #5
pathParam always returns a string. To get a number right away, use pathParamAsClass: it converts the value and checks it.
// src/main/java/com/example/blog/Main.java
config.routes.get("/users/{name}/posts/{id}", ctx -> {
String name = ctx.pathParam("name");
long id = ctx.pathParamAsClass("id", Long.class).get();
ctx.result(name + ", post #" + id);
});The request curl http://localhost:8080/users/anna/posts/3 returns anna, post #3. If text arrives instead of a number, Javalin answers 400 by itself, with a description in JSON:
curl -i http://localhost:8080/users/anna/posts/xHTTP/1.1 400 Bad Request
Content-Type: application/json
{"id":[{"message":"TYPE_CONVERSION_FAILED","args":{},"value":"x"}]}
Query parameters
The values after ? are read with ctx.queryParam. If the parameter is missing, it returns null. For numbers there is queryParamAsClass with a default value:
// src/main/java/com/example/blog/Main.java
config.routes.get("/search", ctx -> {
String q = ctx.queryParam("q");
int limit = ctx.queryParamAsClass("limit", Integer.class).getOrDefault(10);
ctx.result("Search: " + q + ", limit " + limit);
});curl "http://localhost:8080/search?q=java&limit=5"
curl http://localhost:8080/searchSearch: java, limit 5
Search: null, limit 10
Put an address with ? and & in quotes: otherwise the shell treats & as its own symbol.
Method reference
| Method | Result for /search?tag=java&tag=web&limit=5 |
|---|---|
ctx.queryParam("limit") | "5" |
ctx.queryParams("tag") | the list [java, web] |
ctx.queryParamAsClass("limit", Integer.class).get() | 5 |
ctx.queryParamAsClass("page", Integer.class).getOrDefault(1) | 1 |
ctx.queryParamMap() | all parameters as a map |
Common mistake
The name in pathParam must match the name in the route's curly braces. A typo is not visible at compile time:
// src/main/java/com/example/blog/Main.java
config.routes.get("/posts/{id}", ctx -> ctx.result("Post #" + ctx.pathParam("postId")));The client gets 500 Server Error, and the server log shows the reason:
WARN io.javalin.Javalin - Uncaught exception
java.lang.IllegalArgumentException: 'postId' is not a valid path-param for '/posts/{id}'.