What does @RequestMapping annotation?
The @RequestMapping
annotation in Spring Framework is used to map web requests to specific handler methods in a controller. It is a versatile annotation that can be applied at both the class and method levels to define the URL patterns that a particular controller or method should handle.
@RequestMapping
:Mapping URLs: You can specify the URL patterns that the method or class should respond to. For example:
@RequestMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
HTTP Methods: You can specify which HTTP methods (GET, POST, PUT, DELETE, etc.) the mapping should respond to using the method
attribute:
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public String submitForm() {
return "Form submitted!";
}
Request Parameters: You can also map requests based on specific request parameters using the params
attribute:
@RequestMapping(value = "/greet", params = "name")
public String greet(@RequestParam String name) {
return "Hello, " + name + "!";
}
Content Types: The consumes
and produces
attributes allow you to specify the content types that the method can consume or produce:
@RequestMapping(value = "/json", consumes = "application/json", produces = "application/json")
public ResponseEntity<MyResponse> handleJson(@RequestBody MyRequest request) {
// Handle JSON request
}
Path Variables: You can use path variables in the URL mapping:
@RequestMapping("/users/{id}")
public User getUser(@PathVariable String id) {
return userService.findById(id);
}
Class-Level and Method-Level Annotations: You can use @RequestMapping
at the class level to define a base URL for all methods in the controller:
@RequestMapping("/api")
public class ApiController {
@RequestMapping("/users")
public List<User> getUsers() {
// Return list of users
}
}
Here’s a simple example of a Spring controller using @RequestMapping
:
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
@PostMapping("/submit")
public String submit(@RequestBody String data) {
return "Data submitted: " + data;
}
@GetMapping("/users/{id}")
public User getUser(@PathVariable String id) {
return userService.findById(id);
}
}
The @RequestMapping
annotation is a powerful tool in Spring MVC for handling web requests. It provides a flexible way to define how different HTTP requests are routed to specific methods in your controllers, allowing for the creation of RESTful web services and web applications.