@RequestMapping映射的规则

@RequestMapping的映射规则

看了官方文档,才知道 @RequestMapping,除了基本的 pattern 映射,有这么多花样玩儿。

相同URL,不同方法

@RestController
@RequestMapping("/persons")
class PersonController {

    @GetMapping
    public Person getPerson() {
        // ...
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void add(@RequestBody Person person) {
        // ...
    }
}

Get/Post 请求会分别调用不同的handler方法

相同URL,相同方法,不同的请求参数

@GetMapping(path = "/pets/{petId}", params = "pet=dog") 
public void dogs(@PathVariable String petId) {
    // ...
}
@GetMapping(path = "/pets/{petId}", params = "pet=cat") 
public void cats(@PathVariable String petId) {
    // ...
}

请求地址都一样: /pets/1?pet=cat/pets/1?pet=dog但是请求参数不同,调用的方法就不同

相同URL,相同方法,不同的header

@GetMapping(path = "/pets/{petId}", headers= "pet=dog") 
public void dogs(@PathVariable String petId) {
    // ...
}
@GetMapping(path = "/pets/{petId}", headers= "pet=cat") 
public void cats(@PathVariable String petId) {
    // ...
}

跟上面的一样,不同的是通过header参数来区分调用接口。而不是请求参数。

相同的URL,但是请求MediaType不同

@PostMapping(path = "/pets", consumes = "application/json") 
public void addPet(@RequestBody Pet pet) {
    // ...
}
@PostMapping(path = "/pets", consumes = "application/x-www-form-urlencoded") 
public void addPet(Pet pet) {
    // ...
}

根据客户端请求体的 ContentType,来区分调用方法

相同的URL,但是响应的MediaType不同

@GetMapping(path = "/pets/{petId}", produces = "application/json") 
@ResponseBody
public Pet getPet(@PathVariable String petId) {
    // ...
}
@GetMapping(path = "/pets/{petId}", produces = "text/plain") 
@ResponseBody
public Pet getPet(@PathVariable String petId) {
    // ...
}

应该是根据客户端的 Accept 头来区分调用方法(客户端比较容易接受什么ContentType的数据类型)

参考

https://docs.spring.io/spring/docs/5.2.5.RELEASE/spring-framework-reference/web.html#mvc-ann-requestmapping

1 个赞

学习了