Explain @RequestMapping annotation.
Explain @RequestMapping annotation.
The @RequestMapping
annotation in Spring MVC is a fundamental tool used for mapping web requests to specific handler methods within controller classes. This annotation is versatile and can be applied at both the class and method levels, allowing for flexible handling of HTTP requests in a Spring MVC application.
@RequestMapping
is used to map URLs to controller methods. It helps in directing incoming web requests to the appropriate handler functions based on the URL path, HTTP method, and other request parameters. When applied at the class level, it defines a basic or root path, and when specified at the method level, it provides further specification that builds upon the base path defined at the class level.
The annotation supports various HTTP methods like GET, POST, PUT, DELETE, etc., through its method
attribute. This allows developers to handle different types of client requests under the same URL pattern but with different methods. For example, you might have one method in a controller handle GET
requests for retrieving data, while another handles POST
requests for submitting data.
@Controller
@RequestMapping("/products")
public class ProductController {
@RequestMapping(method = RequestMethod.GET)
public String getAllProducts() {
// Method implementation
return "products";
}
@RequestMapping(method = RequestMethod.POST)
public String addProduct(Product product) {
// Method implementation
return "redirect:/products";
}
}
@RequestMapping
can also handle more complex scenarios such as mapping requests based on header values, request parameters, or producing specific content types. This is useful for creating APIs that respond differently based on a...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào