如图,今天在学习 springboot 时犯了个很低级的错,遇到了这个错误。

背景
前端
// 文章删除
export const articleCategoryDeleteService = (categoryId) => {
return request.delete('/category?id=' + categoryId)
}
后端
@DeleteMapping("/category/categoryId")
public Result delete(@PathParam("categoryId") Integer id){
categoryService.delete(id);
return Result.success();
}
解决
将后端代码中的 categoryId 去掉
@DeleteMapping("/category")
public Result delete(@PathParam("categoryId") Integer id){
categoryService.delete(id);
return Result.success();
}
@PathVariable 和 @PathParam
这里顺便记录下 @PathVariable 和 @PathParam 获取参数的方式,例如前端请求路径为
http://localhost:8080/springmvc/hello/101?param1=10¶m2=20
此时后端的方法为
@RequestMapping("/hello/{id}")
public String getDetails(@PathVariable(value="id") String id,
@RequestParam(value="param1", required=true) String param1,
@RequestParam(value="param2", required=false) String param2){
.......
}
若参数为从URL 模板中获取,例如 ***/user/1,那么在后端要获取 1 这个参数是就要用 @PathVariable,且在后端方法中要写上 ({/id}) 形式的参数,而如果是 ?param10=1¶m2=20 这种的则需要用 @PathParam 接受,并且在后端方法中不用携带相对应的参数。
总结
如果只是 ID 这种单个或者多个数字字母,使用 @PathVariable 是非常好的选择,但是如果是获取多个参数,而且是不同类型的,那么最好使用 @PathParam。
作者在学习SpringBoot时遇到关于前端与后端接口匹配的低级错误,发现后端`@DeleteMapping`中的`categoryId`多余,导致URL路径解析问题。文章详细介绍了`@PathVariable`和`@PathParam`的区别,推荐在处理单一ID时使用`@PathVariable`,处理复杂参数时选用`@PathParam`。
3210

被折叠的 条评论
为什么被折叠?



