Get method with path variables

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:

    private static final String helloWorldTemplate = "Hello World, 
%s!";

@GetMapping("/welcome-with-parameter/name/{name}")
public WelcomeBean welcomeWithParameter(@PathVariable String name)
{
return new WelcomeBean(String.format(helloWorldTemplate, name));
}

A few important things to note are as follows:

  • @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.
  • String.format(helloWorldTemplate, name): A simple string format to replace %s in the template with the name.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset