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.
|
|
When the URL is called, it matches this @Path annotation and my-id
is passed to the method as the id
parameter.
|
|
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.
|
|
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.
|
|
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.
|
|
This is one possible URL that matches the path and the regex inside it:
|
|
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.