Using the Spring @RequestMapping Annotation

发布时间 2023-03-23 14:45:29作者: HelloMarsMan

 @RequestMapping is one of the most common annotation used in Spring Web applications. This annotation maps HTTP requests to handler methods of MVC and REST controllers. 

In this post, you’ll see how versatile the @RequestMapping annotation is when used to map Spring MVC controller methods. 

Request Mapping Basics

In Spring MVC applications, the RequestDispatcher (Front Controller Below) servlet is responsible for routing incoming HTTP requests to handler methods of controllers. 

When configuring Spring MVC, you need to specify the mappings between the requests and handler methods.

Spring MVC Dispatcher Servlet and @RequestMapping

To configure the mapping of web requests, you use the @RequestMapping annotation. 

The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. 

The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.

Here is an example of the @RequestMapping annotation applied to both class and methods.

 

@RestController
@RequestMapping("/home")
public class IndexController
{
@RequestMapping("/")
String get()
{
//mapped to hostname:port/home/
return "Hello from get";
}
 
@RequestMapping("/index")
String index()
{
//mapped to hostname:port/home/index/
return "Hello from index";
}
}
 

With the preceding code, requests to /home will be handled by get() while request to /home/index will be handled by index()

@RequestMapping with Multiple URIs

You can have multiple request mappings for a method. For that add one @RequestMapping annotation with a list of values. 

 

@RestController
@RequestMapping("/home")
public class IndexController
{
@RequestMapping(value={"", "/page", "page*","view/*,**/msg"})
String indexMultipleMapping()
{
return "Hello from index multiple mapping.";
}
}
 

As you can see in this code, @RequestMapping supports wildcards and ant-style paths. For the preceding code, all these URLs will be handled by indexMultipleMapping() 

  • localhost:8080/home
  • localhost:8080/home/
  • localhost:8080/home/page
  • localhost:8080/home/pageabc
  • localhost:8080/home/view/
  • localhost:8080/home/view/view