Request Mapping

Basic Spring
≈ 2 min read

How a request finds a controller method

Spring MVC connects HTTP requests to controller methods through mapping annotations. A mapping usually includes the path and HTTP method. The most general option is @RequestMapping, while specific HTTP methods have shorter annotations: @GetMapping, @PostMapping, @PutMapping, @PatchMapping, and @DeleteMapping.

@RestController
@RequestMapping("/orders")
class OrderController {

    @GetMapping("/{id}")
    OrderDto find(@PathVariable long id) {
        return orderService.find(id);
    }

    @PostMapping
    OrderDto create(@RequestBody CreateOrderRequest request) {
        return orderService.create(request);
    }
}

The class-level mapping defines the common /orders prefix. Method-level mappings refine the path and HTTP operation: the first method handles GET /orders/{id}, while the second handles POST /orders.

One URL does not mean one handler

The same path can have different methods for different HTTP operations. This lets you use one resource URL while clearly separating reading, creating, updating, and deleting. A mapping can also consider additional request conditions, but for most endpoints a well-chosen path and the appropriate specialized annotation are enough.

Choose the HTTP method according to the meaning of the operation. A mapping is part of the API's external contract, so GET should not be used for an operation that changes state just because the URL is easier to call from a browser.