In Spring Boot, request mappings define how HTTP requests are mapped to specific handler methods in a controller. Spring provides several annotations to handle different types of HTTP requests. Here are the different types of request mappings in Spring Boot:
- @RequestMapping: General-purpose mapping capable of handling multiple HTTP methods.
- @GetMapping: Handles HTTP GET requests.
- @PostMapping: Handles HTTP POST requests.
- @PutMapping: Handles HTTP PUT requests.
- @DeleteMapping: Handles HTTP DELETE requests.
- @PatchMapping: Handles HTTP PATCH requests.
1. @RequestMapping
- Purpose: General-purpose mapping annotation that can handle all types of HTTP methods (GET, POST, PUT, DELETE, etc.) depending on its configuration.
- Usage:
@RequestMapping(value = "/path", method = RequestMethod.GET) public String handleGetRequest() { return "response"; }
2. @GetMapping
- Purpose: Handles HTTP GET requests, typically used for fetching resources.
- Usage:
@GetMapping("/path") public String handleGetRequest() { return "response"; }
3. @PostMapping
- Purpose: Handles HTTP POST requests, typically used for creating or submitting data.
- Usage:
@PostMapping("/path") public String handlePostRequest(@RequestBody Data data) { return "response"; }
4. @PutMapping
- Purpose: Handles HTTP PUT requests, typically used for updating resources.
- Usage:
@PutMapping("/path") public String handlePutRequest(@RequestBody Data data) { return "response"; }
5. @DeleteMapping
- Purpose: Handles HTTP DELETE requests, typically used for deleting resources.
- Usage:
@DeleteMapping("/path") public String handleDeleteRequest() { return "response"; }
6. @PatchMapping
- Purpose: Handles HTTP PATCH requests, typically used for partially updating resources.
- Usage:
@PatchMapping("/path") public String handlePatchRequest(@RequestBody Data data) { return "response"; }
7. @RequestMapping with Multiple Methods
- Purpose: You can use
@RequestMapping
to handle multiple HTTP methods for a single handler. - Usage:
@RequestMapping(value = "/path", method = {RequestMethod.GET, RequestMethod.POST}) public String handleGetAndPostRequests() { return "response"; }