Let's shift our attention to path variables. Path variables are used to bind values from the URI to a variable on the controller method. In the following example, we want to parameterize the name so that we can customize the welcome message with a name:
@GetMapping("/welcome-with-parameter/name/{name}")
fun welcomeWithParameter(@PathVariable name: String) =
WelcomeBean("Hello World, $name")
The following are a few important things to note:
- @GetMapping("/welcome-with-parameter/name/{name}"): {name} indicates that this value will be the variable. We can have multiple variable templates in a URI.
- welcomeWithParameter(@PathVariable String name): @PathVariable ensures that the variable value from the URI is bound to the variable name.
- fun welcomeWithParameter(@PathVariable name: String) = WelcomeBean("Hello World, $name"): We are using the Kotlin single expression function declaration to directly return the created WelcomeBean. "Hello World, $name" makes use of Kotlin string templates. $name will be replaced by the value of the path variable name.