A Variable in the Path
Put a placeholder in the address and greet anyone by name.
1import org.springframework.web.bind.annotation.*;
2
3@RestController
4public class GreetingController {
5 @GetMapping("/hello/{name}")
6 public String hello(@PathVariable String name) {
7 return "Hello, " + name + "!";
8 }
9}
$ ./mvnw spring-boot:run
:: Spring Boot :: (v3.3.0)
Tomcat started on port 8080 (http)
Started DemoApplication in 1.24 seconds
$ curl localhost:8080/hello/Ada
Hello, Ada!
$ curl localhost:8080/hello/Grace
Hello, Grace!
Every line, explained
import org.springframework.web.bind.annotation.*;- This import brings in Spring's web annotations (@RestController, @GetMapping and friends). The .* means "everything in this package", which saves one import line per annotation.
@RestController- @RestController is an annotation: a label that starts with @ and gives Spring information about your class. This one says "this class answers web requests, and whatever its methods return should be sent back to the caller". You never call this class yourself; Spring creates it and calls it for you.
public class GreetingController {- A controller is a perfectly ordinary Java class; the annotations are what make it special.
@GetMapping("/hello/{name}")- The curly braces make {name} a placeholder: this endpoint matches /hello/Ada, /hello/Grace, /hello/anything. Whatever is in that spot of the address gets captured under the name "name".
public String hello(@PathVariable String name) {- @PathVariable connects the placeholder to the parameter: the captured piece of the address arrives here as the String name. Request /hello/Ada, and inside this method name is "Ada".
return "Hello, " + name + "!";- Plain old string joining from Intro to Java, but now the value came from the web address. Every visitor can get a different answer from the same method.
}- This } closes the method.
}- This } closes the class.