Contents

Jakarta @PathParam annotation

Writen by: David Vlijmincx

Introduction

In this short post, we cover how to read values from a path template. The path template is specified inside the @Path and can be used as a source for method parameters.

Mapping a single value

The following example has a single path parameter called id. You specify a parameter by placing the name of the parameter between two brackets. For example, if you want a path parameter called id you specify it like this {id}. The id is used inside the @Path("/path/{id}") and inside @PathParam("id"). By making this connection, we know what path parameter belongs to which method parameter.

1
2
3
4
5
6
@GET
@Path("/path/{id}")
@Produces(MediaType.APPLICATION_JSON)
public String simplePathParam(@PathParam("id") String id){
    return "Received id: " + id;
}

When the URL is called, it matches this @Path annotation and my-id is passed to the method as the id parameter.

1
localhost:8080/path/my-id

Mapping multiple values

You can also specify multiple values inside your path template. You do this by repeating the {anyValue} as many times as you need. In the following example, I needed two values one for id and one for username.

1
2
3
4
5
6
@GET
@Path("/path/{id}/{username}")
@Produces(MediaType.APPLICATION_JSON)
public String simplePathParam(@PathParam("id") String id, @PathParam("username") String username){
    return "Received id: " + id + " username:" + username;
}

Notice that I also have two @PathParam annotations that have the same name as those used inside the path template.

The following URL matches that of the @Path parameter. My-id is going to be used as id inside the method and my-username is used as the username.

1
localhost:8080/path/my-id/my-usename

Path regex

You can use Regex inside the @Path annotation to do some validation on the path. This will result in your method parameter values also matching this regex. This saves you from doing some of the validation yourself inside the method as you can let the framework handle it for you.

In the following example, I added two regexes.

  • The id has to be a number that can only be 3 to 5 numbers long.
  • The username has to be all uppercase and between 0 and 5 characters.
1
2
3
4
5
6
@GET
@Path("regex/path/{id:\\d{3,5}}/{username:[A-Z]{0,5}}")
@Produces(MediaType.APPLICATION_JSON)
public String optionalPathParam(@PathParam("id") int id, @PathParam("username") String username) {
    return "Received id: " + id + " " + username;
}

This is one possible URL that matches the path and the regex inside it:

1
localhost:8080/regex/path/111/FFF

Conclusion

You use the @PathParam to get values from the matching @Path template as input for your methods. The PathParam name has to match the name inside the brackets of the Path. We also saw that you can apply a regex to the path to do some validation on the path and the parameters.