Mapping Requests to Handler Methods
@RequestMapping is the base annotation Spring MVC uses to bind a URL pattern (and optionally an HTTP method) to a controller class or method. Applied at the class level, it defines a common prefix for every handler inside; applied at the method level, it appends a more specific path or narrows the method further. Without this mapping, the DispatcherServlet has no way to route an incoming HTTP request to the correct Java method.
Cricket analogy: It's like a stadium's gate numbering system: the class-level mapping is the stand ('Block A'), and each method-level mapping is a specific gate ('Gate A3') that routes exactly the right ticket holders (requests) to the right seats.
HTTP Method Shortcuts
Rather than writing @RequestMapping(method = RequestMethod.GET) repeatedly, Spring provides composed annotations: @GetMapping, @PostMapping, @PutMapping, @PatchMapping, and @DeleteMapping. These are shorthand for @RequestMapping restricted to a single HTTP verb, and using them makes a controller's intent immediately readable — a @DeleteMapping clearly signals a destructive operation without reading further into the method body.
Cricket analogy: Like the shorthand scoring notation on a scorecard ('4', '6', 'W') instead of writing 'four runs scored' every time — @GetMapping and friends are the concise shorthand for @RequestMapping(method=...).
@RestController
@RequestMapping("/api/orders")
public class OrderController {
@GetMapping("/{orderId}/items/{itemId}")
public OrderItemDto getOrderItem(
@PathVariable Long orderId,
@PathVariable("itemId") Long itemId) {
return orderService.findItem(orderId, itemId);
}
@GetMapping
public List<OrderDto> searchOrders(
@RequestParam(required = false) String status,
@RequestParam(defaultValue = "0") int page) {
return orderService.search(status, page);
}
}Path Variables vs Request Parameters
@PathVariable extracts a value embedded directly in the URL path, such as the orderId in /api/orders/42 — it identifies a specific resource and is typically required. @RequestParam, in contrast, extracts values from the query string (?status=SHIPPED&page=1) and is well suited for optional filters, pagination, or sorting options. Choosing the right one matters for URL design: identifiers belong in the path, optional modifiers belong in the query string.
Cricket analogy: A path variable is like a player's fixed jersey number identifying exactly who they are (e.g., '18' for Virat Kohli), while a request parameter is like an optional filter such as 'format=ODI' applied to a stats query.
If a @PathVariable name doesn't match the method parameter name exactly, specify it explicitly: @PathVariable("itemId") Long itemId. Since Java 8+ with -parameters compiler flag, Spring can often infer it automatically, but being explicit avoids surprises.
Combining Class-Level and Method-Level Mappings
When a class carries @RequestMapping("/api/orders") and a method carries @GetMapping("/{orderId}"), Spring concatenates them into /api/orders/{orderId}. This layering lets you group all endpoints for a resource under one base path while keeping individual method mappings short and specific, which also makes bulk changes (like versioning a whole resource to /api/v2/orders) a one-line edit at the class level.
Cricket analogy: Like a tournament's fixed venue prefix ('Wankhede Stadium') combined with a specific match code — changing the venue for a whole series means editing just the one shared prefix.
Overlapping mappings across controllers (e.g., two methods both matching GET /api/orders/{id}) cause Spring to throw an ambiguous mapping exception at startup. Keep resource paths unique per controller and verify with your app's actuator /mappings endpoint if unsure.
- @RequestMapping binds URL patterns (and optionally HTTP methods) to controller classes or methods.
- @GetMapping, @PostMapping, @PutMapping, @PatchMapping, and @DeleteMapping are HTTP-verb shorthand for @RequestMapping.
- Class-level and method-level mappings concatenate to form the full endpoint path.
- @PathVariable extracts required identifiers embedded in the URL path itself.
- @RequestParam extracts optional query-string values like filters, sorting, and pagination.
- Mismatched @PathVariable names should be specified explicitly to avoid binding errors.
- Overlapping route definitions across controllers cause an ambiguous mapping error at startup.
Practice what you learned
1. What happens when @RequestMapping is applied at both the class and method level?
2. Which annotation would you use to extract an optional query-string filter like ?status=SHIPPED?
3. What is @GetMapping shorthand for?
4. What happens if two controller methods define an identical, overlapping route mapping?
5. Which is the correct use of @PathVariable when the URL segment name differs from the method parameter name?
Was this page helpful?
You May Also Like
Building REST Controllers
Learn how to build REST controllers in Spring Boot using @RestController, structure methods cleanly, and return well-formed HTTP responses.
Request and Response Bodies
Learn how Spring Boot serializes and deserializes JSON request and response bodies using @RequestBody, @ResponseBody, and Jackson.
Validation in Spring Boot
Learn how to validate incoming request data in Spring Boot using Bean Validation annotations, @Valid, and custom validators.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics
Web DevelopmentNext.js Study Notes
JavaScript · 30 topics