Clean β’ Professional
@RequestMapping is a core Spring annotation that maps HTTP requests to controller methods. It allows specifying URLs, HTTP methods (GET, POST, PUT, DELETE, etc.), request and response content types (like JSON or XML), and headers (useful for API versioning or access control). It forms the foundation of request routing in Spring MVC and Spring Boot.
@RequestMapping is used to:
GET, POST, PUT, DELETE)consumes and produces content types (e.g., JSON, XML)β οΈ Default behavior: If the HTTP method is not specified, @RequestMapping matches all HTTP methods.
Caution: Itβs best to specify the HTTP method to avoid unintended matches.
Basic Example
@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<User>getUsers() {
return userService.findAll();
}
value β URL pathmethod β HTTP method (GET, POST, etc.)Defines a base URL for all methods in a controller.
@RestController
@RequestMapping("/api/users")
publicclassUserController { }
Defines specific endpoints under the base URL.
@GetMapping
public List<User>getAllUsers() {
return userService.findAll();
}
Final URL: /api/users

Spring provides shortcuts over @RequestMapping(method=...) for clarity:
@GetMapping β GET β Fetch resource(s)@PostMapping β POST β Create resource@PutMapping β PUT β Update full resource@PatchMapping β PATCH β Partial update@DeleteMapping β DELETE β Remove resourcePrefer these shortcuts for cleaner and more readable code.
| Attribute | Purpose |
|---|---|
path / value | Map URL path(s), supports arrays ({"/users","/members"}) and wildcards (*,**) |
method | Specify HTTP method(s) |
consumes | Accept only requests with a specific Content-Type (application/json) |
produces | Return responses with a specific Content-Type (application/json) |
headers | Match requests containing specific headers (X-API-VERSION=1) |
Examples
// Consume JSON and produce JSON
@PostMapping(consumes = "application/json", produces = "application/json")
public UsersaveUser(@RequestBody User user) {
return user;
}
// Handle multiple HTTP methods
@RequestMapping(value = "/status", method = {RequestMethod.GET, RequestMethod.POST})
public Stringstatus() {
return"OK";
}
// Path variable with regex
@GetMapping("/users/{id:[0-9]+}")
public UsergetUser(@PathVariable Long id) {
return userService.findById(id);
}
// Multiple paths
@RequestMapping(value = {"/users", "/members"}, method = RequestMethod.GET)
public List<User>getAll() {
return userService.findAll();
}
@GetMapping, @PostMapping) for readability@RequestMapping for base URLs/api/v1/usersX-API-VERSION=1Accept=application/vnd.company.v1+json@Valid@RequestMapping is the foundation of request routing in Spring MVC and Spring Boot.
@GetMapping, @PostMapping, etc.)