TL;DR
It is used to map web requests to Spring Controller methods.
In Spring Web applications, @RequestMapping is one of the most used annotations. HTTP requests are mapped to MVC and REST controller handler methods with this annotation.
URL handler using @RequestMapping annotation as it follows here:
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
The alternative approach in other words possible short version is:
@GetMapping("/get/{id}")
We can also implement other mappings mentioned below:
To sum up, it is a better approach to use RequestMapping or alternative mapping in class level controllers since all your requests and responses will be handled in controller. Here is a full code example:
@Controller
@RequestMapping(value = "/orders", method = RequestMethod.GET)
public class DemoController {
@RequestMapping(value = "/{orderId}", method = RequestMethod.GET)
@ResponseBody
public String getOrder(@PathVariable final String orderId) {
return "Order ID: " + orderId;
}
@RequestMapping(value = "/addProduct", method = RequestMethod.POST)
public String addProductPost(@ModelAttribute("product")
Product product) {
// some code
}
// other mappings
// ...
}
Top comments (0)