yl-backend/docs/一个非常奇怪的错误.md

28 lines
885 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

问题 本质原因
访问 POST 接口用 GET路径又模糊匹配 Spring 把你写的 testMethod 误当成其他接口的参数,比如 {id},尝试类型转换失败
预期 405 报错却看到类型转换失败 是路径匹配到了别的接口,没走到你定义的方法
解决办法 用正确的请求方式 / 添加明确前缀 / 避免通配路径冲突
现在有这个一个方法
```java
@GetMapping("{id}")
public Result<Course> queryById(@PathVariable("id") Integer id) {
return Result.success(courseService.getById(id));
}
```
我又写了一个方法
```java
@PostMapping("/testMethod")
public void testMethod(@RequestParam(name = "page") Long pageNum){
}
```
然后我请求
```java
GET http://localhost:8084/bs/courses/testMethod?page=1
```
请求其实走到了上面
Spring 的路径匹配是优先按 URL 结构匹配方法类型GET/POST其次。