Spring @RequestMapping 注解使用

用于 spring mvc 中的controller 配置 url 访问地址

代码示例

  • 注解在类 和 方法上
@RestController
@RequestMapping("/hello")
public class HelloController
{
  @RequestMapping("/sayHello")
  public String sayHello()
  {
    return "hello spring boot!";
  }
}

访问地址为

127.0.0.1:8080/hello/sayHello

  • @RequestMapping 来处理多个 URI
@RestController
@RequestMapping("/hello")
public class HelloController
{
  @RequestMapping(value = {  
       "/sayHello",  
       "/say",  
       "page*",  
       "view/*,**/msg"  
   })  
  public String sayHello()
  {
    return "hello spring boot!";
  }
}

访问地址:

  • 127.0.0.1:8080/hello/sayHello
  • 127.0.0.1:8080/hello/page
  • 127.0.0.1:8080/hello/pageabc
  • 127.0.0.1:8080/hello/view/
  • 127.0.0.1:8080/hello/view/view

用 @RequestMapping 处理 HTTP 的各种方法

@RestController
@RequestMapping("/hello")
public class HelloController
{
  @RequestMapping(value = "/get", method = RequestMethod.GET)  
  String get() {  
      return "Hello from get";  
  }  
  @RequestMapping(value = "/delete",method = RequestMethod.DELETE)  
  String delete() {  
      return "Hello from delete";  
  }  
  @RequestMapping(value = "/post",method = RequestMethod.POST)  
  String post() {  
      return "Hello from post";  
  }  
  @RequestMapping(value = "/put",method = RequestMethod.PUT)  
  String put() {  
      return "Hello from put";  
  }  
  @RequestMapping(value = "/patch",method = RequestMethod.PATCH)  
  String patch() {  
      return "Hello from patch";  
  }  
}

使用 @RequestMapping 处理动态 URI

@RestController
@RequestMapping("/hello")
public class HelloController
{
    @RequestMapping(value = "/fetch/{id}", method = RequestMethod.GET)  
    String getDynamicUriValue(@PathVariable String id) {  
       System.out.println("ID is " + id);  
       return "Dynamic URI parameter fetched";  
    }  
    @RequestMapping(value = "/fetch/{id:[a-z]+}/{name}", method = RequestMethod.GET)  
    String getDynamicUriValueRegex(@PathVariable("name") String name) {  
       System.out.println("Name is " + name);  
       return "Dynamic URI parameter fetched using regex";  
    }  
}

@RequestMapping 快捷方式

Spring 4.3 引入了方法级注解的变体,也被叫做 @RequestMapping 的组合注解。 组合注解可以更好的表达被注解方法的语义。 它们所扮演的角色就是针对 @RequestMapping 的封装,而且成了定义端点的标准方法。

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping