Controller RequestMapping
In Spring MVC, @RequestMapping is like a GPS that tells the application which method should handle which URL. It is the most important annotation for routing requests.
You can use @RequestMapping at two levels:
- Class level – defines a base URL for all methods in the controller.
- Method level – defines the specific URL for that method.
Spring also provides shortcut annotations for HTTP methods:
- @GetMapping – handles GET requests (viewing data).
- @PostMapping – handles POST requests (creating data).
- @PutMapping – handles PUT requests (updating data).
- @DeleteMapping – handles DELETE requests (deleting data).
- @PatchMapping – handles PATCH requests (partial updates).
Here are examples of different mappings:
@RestController
@RequestMapping("/api/users")
public class UserController {
// GET /api/users
@GetMapping
public List getAllUsers() { ... }
// GET /api/users/5
@GetMapping("/{id}")
public User getUserById(@PathVariable int id) { ... }
// POST /api/users
@PostMapping
public User createUser(@RequestBody User user) { ... }
// PUT /api/users/5
@PutMapping("/{id}")
public User updateUser(@PathVariable int id, @RequestBody User user) { ... }
// DELETE /api/users/5
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable int id) { ... }
}
You can also use parameters, headers, and content type for more precise mapping:
@GetMapping(value = "/search", params = "q")
public String search(@RequestParam String q) { ... }
@PostMapping(consumes = "application/json", produces = "application/json")
public User createJsonUser(@RequestBody User user) { ... }
Two Minute Drill
- @RequestMapping maps URLs to controller methods.
- Use shortcut annotations: @GetMapping, @PostMapping, etc.
- @PathVariable captures values from URL template.
- @RequestParam captures query parameters.
- Class-level @RequestMapping adds a common prefix.
Need more clarification?
Drop us an email at career@quipoinfotech.com
