0%

Http请求映射·RequestMapping

@RequestMapping 是 Spring Web 应用程序中最常被用到的注解之一,用于实现Http请求映射,实现指定请求 路径、方式、参数、请求头、Content-Type 的功能。
下面记录此注解的常用参数和SpringBoot中提供的与之有关的组合注解(@GetMapping @PostMapping 等)。

@RequestMapping 注解的位置

@RequestMapping 注解可以使用在 方法 之上 。使用在类上则本类中所有其他@RequestMapping的映射都要先满足类上注解的要求。

关于注解的使用位置,我吗可以通过源码获知,如此处的源码中(追踪注解)有如下内容:

1
@Target({ElementType.TYPE, ElementType.METHOD})

则表示可使用于(TYPE) 和 方法(METHOD)之上

指定请求路径与方式

可以通过指定@RequestMapping的 value属性(或path) 来指定请求路径,指定method属性 来指定请求方式。
value属性需要以String类型提供,method属性需要以RequestMethod的枚举类型提供。接受的RequestMethod枚举类型如下:

1
2
3
4
5
6
7
8
9
10
public enum RequestMethod {
GET,
HEAD,
POST,
PUT,
PATCH,
DELETE,
OPTIONS,
TRACE;
}

SpringBoot提供了针对请求方法的合成注解供使用:

  • @PostMapping 等价于 @RequestMapping(method = RequestMethod.POST)
  • @GetMapping 等价于 @RequestMapping(method = RequestMethod.GET)
  • @PutMapping 等价于 @RequestMapping(method = RequestMethod.PUT)
  • @DeleteMapping 等价于 @RequestMapping(method = RequestMethod.DELETE)

代码示例:

1
2
3
4
5
@RequestMapping(value = "/testMethod", method = RequestMethod.POST)
public String testMethod(){
System.out.println("testMethod 处理了请求");
return "success testMethod 测试成功";
}

Tips

  1. 当只指定请求路径时,不需要特别写 value 的属性名。直接写一个String类型即可。
  2. 当不知到属性注定所需的参数时,可以追踪源码。点击 属性名-再点击参数类型 即可看到。

指定请求参数

使用params属性指定。
可以指定 没有 某个参数:params = "参数名"params = "!参数名"
也可以指定参数 不是 某个值:params = "参数名=参数值"params = "参数名!=参数值"

代码示例:

1
2
3
4
5
@RequestMapping(value = "/testParams", method = RequestMethod.GET, params = "code!=hello")
public String testParams(){
System.out.println("testParams 处理了请求");
return "testParams 测试成功";
}

指定请求头

使用headers属性指定,设置方式与指定请求参数相似。
可以指定 没有 某个请求头:headers = "请求头名"headers = "!请求头名"
也可以指定参数 不是 某个值:params = "请求头名=请求头值"params = "请求头名!=请求头值"

代码示例:

1
2
3
4
5
@RequestMapping(value = "/testHeaders2", method = RequestMethod.GET, headers = "deviceType=ios")
public String testHeaders2(){
System.out.println("testHeaders2 处理了请求");
return "testHeaders2 测试成功";
}

指定请求头的Content-Type

使用consumes属性指定,设置方式与指定请求参数相似。
也可以指定Content-Type头 不是 某个值:consumes = "Content-Type头的值"consumes = "!Content-Type头的值"

代码示例:

1
2
3
4
5
@RequestMapping(value = "/testConsumes", method = RequestMethod.GET, consumes = "multipart/form-data")
public String testConsumes(){
System.out.println("testConsumes 处理了请求");
return "testConsumes 测试成功";
}