Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 casts the id route parameter to the userId method argument. Similarly, the field route parameter is passed as String to showUserField().

An incorrect route such as /user/test/email (it's incorrect because the test substring cannot be converted to...