Using dynamic route parameters in a controller method
Now we will define dynamic segments for a route and use them in the associated controller method. For example, we want the /user/5/name
and /user/6/email
routes to execute the same controller method with different arguments: showUserField(5, "name")
and showUserField(6, "email")
, respectively.
How to do it…
Use {}
to enclose the dynamic route segments and @PathVariable
to annotate the corresponding controller method arguments:
@RequestMapping("/user/{id}/{field}") public void showUserField(@PathVariable("id") Long userId, @PathVariable("field") String field) { ... }
How it works…
A request for the /user/5/email
route will execute the showUserField(5,"email")
method. @PathVariable("id") Long userId ...
Get Spring Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.