The previously defined HomeController class has only one handler method, and this method is annotated with the @RequestMapping annotation. Here, I have used two attributes of this annotation--one is value to map the HTTP request to the / pattern, and the other attribute is a method for supporting the HTTP GET method. We can define multiple URL mappings with one handler method. Let's see this in the following code snippet:
@Controller public class HomeController { @RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET) public String home (){ return "home"; } }
In the preceding code, the @RequestMapping annotation has an array of string values for the value attribute of this annotation. Now, this handler method is mapped with two URL patterns, such as / and /index. The Spring MVC's @RequestMapping annotation supports several HTTP methods such as GET, POST, PUT, DELETE, and so on. As of version 4.3, Spring composed @RequestMapping variants, and now provides simple methods for the mapping of common HTTP methods, as shown in the following expressions:
@RequestMapping + HTTP GET = @GetMapping @RequestMapping + HTTP POST = @PostMapping @RequestMapping + HTTP PUT = @PutMapping @RequestMapping + HTTP DELETE = @DeleteMapping
This is the modified version of HomeController with composed annotation mappings:
@Controller public class HomeController { @GetMapping(value = {"/", "/index"}) public String home (){ return "home"; } }
We can use the @RequestMapping annotation at both locations: at the class level, and at the method level. Let's see examples for this: