We have seen that the DispatcherServlet uses a HandlerMapping to determine how incoming requests are handled.
By default, Spring Web MVC will install and use a RequestMappingHandlerMapping that allows us to use annotations to determine which controller and method to use.
The following block diagram shows a typical relationship between the various components:
Any component will be inspected for a @RequestMapping annotation. If this annotation is present, a mapping will be created depending on the path attribute. In addition, the method annotation specifies the HTTP method for the mapping. To make it more obvious that the given Bean is meant to be a controller, there is a special @Controller annotation that can be used on the class.
Since Spring 4.3, there have been convenience annotations for each HTTP method. These annotations are called @GetMapping, @PostMapping, and so on.
If the @RequestMapping annotation is present on the class level, it is used as a prefix for all methods that are annotated with @RequestMapping or any of the method-specific annotations:
@Controller
@RequestMapping("/posts")
public class RequestMappingPostController {
@RequestMapping(path = "/newest", method = RequestMethod.GET)
// […]
// public String addPost(@RequestBody Post post) {
// This method will be mapped to
// POST requests with the path /posts
}
}
Go to https://bit.ly/2MsHOvc to access the complete code for the @RequestMapping annotation example.