liveBook · Manning

Path variable

As explained in Spring Start Here, Second Edition

A path variable is a value conveyed within a request path, typically as a variable segment of a resource URI.

A path variable carries a small value inside the request path. Use it when the value is mandatory and central to the requested page; use a request parameter for optional values. section 8.1.1 section 8.1.3

Listing 8.4 Using path variables to get values from the client
@Controller
public class MainController {
 
  @RequestMapping("/home/{color}") #A
  public String home(
      @PathVariable String color,    #B
      Model page) {
    page.addAttribute("username", "Katy");
    page.addAttribute("color", color);
    return "home.html";
  }
}

In Spring MVC, put a named variable in the route between curly braces, then annotate the matching controller parameter with @PathVariable. The example captures the color from /home/blue. section 8.1.3

Choose path variables when:

  • The value is required and one or two values make the request easier to read. section 8.1.3
  • Avoid optional values and long lists of path variables; request parameters suit optional values and are preferred for more than two. section 8.1.3

How Spring Start Here, Second Edition covers it

How deep it goes
Defines positional path values and demonstrates curly-brace mappings with @PathVariable, while limiting advice to small numbers of values.
Examples
Demonstrates a /home/{color} route that captures values such as blue, red, and green.
What you can do after
Apply Spring MVC’s @PathVariable to bind a mandatory path segment to a controller parameter.
How it connects
Distinguishes path variables from request parameters and request bodies, and connects them to controller actions.

Also explained in

Compare how 3 books explain path variable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.