Card 02/ 06
Request Mapping Example: Reading the Path, the Query String and the Body
A request carries data in three places, and each place has its own annotation.
A request can carry data in three places: in the path (/rides/42), in the query string after the ? (?status=active), and in the body, usually as JSON. A controller method, a method on the class that answers web requests, reads each with its own annotation: @PathVariable, @RequestParam and @RequestBody.
The controller below uses all three. @RequestMapping("/rides") on the class puts /rides in front of every method's path:
@RestController
@RequestMapping("/rides")
class RideController {
@GetMapping("/{id}")
ResponseEntity<Ride> getRide(@PathVariable String id) { /* ... */ }
@GetMapping
ResponseEntity<?> list(@RequestParam(defaultValue = "all") String status) { /* ... */ }
@PostMapping
ResponseEntity<Ride> createRide(@RequestBody Ride ride) { /* ... */ }
}| Annotation | Reads from | Example |
|---|---|---|
@PathVariable | A segment of the URL itself | /rides/42 gives id = "42" |
@RequestParam | The query string | /rides?status=active gives status = "active" |
@RequestBody | The request body, converted from JSON by Jackson, Boot's JSON library, | A JSON object becomes a Ride |
@RequestParam(defaultValue = "all") makes the parameter optional, so /rides with no query string gets status = "all". Without a default, a request that leaves the parameter out is rejected with 400 Bad Request.
So each piece of request data has one obvious home: the identity of a resource in the path, filters and options in the query string, and the thing being created or changed in the body.
← → move through sections and cards