Path Variables
A path variable is a part of the address that changes with each request. The method reads that part and uses it in the answer.
Mark the changing part
The brackets mark name as the part that changes.
@GetMapping("/greet/{name}")Read the changing part
This annotation reads the name from the address.
public String greet(@PathVariable String name) {Ask with a name
This command asks for a greeting for Ana.
curl http://localhost:8080/greet/AnaExample
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetController {
@GetMapping("/greet/{name}")
public String greet(@PathVariable String name) {
return "Hello, " + name + "!";
}
}Key points
- A path variable is a part of the address that changes.
- Curly brackets in the address mark the changing part.
- @PathVariable is the annotation that reads the changing part.
- The annotation sits on the method parameter.
- The name in the brackets must match the parameter name.
- A visit to /greet/Ana puts Ana in the answer.
In this example, the annotation marks GreetController as a controller. The @GetMapping line ties the method to the address /greet/{name}. The brackets mark name as the part that changes. The @PathVariable annotation reads the name from the address. The method joins Hello with the name and an exclamation mark. A request to /greet/Ana gets the text Hello, Ana!
Note
The changing part is text, so the method takes a String.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What marks the changing part of an address?