You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中嵌套@DeleteMapping无法捕获URI@PathVariable问题

问题分析与解决方案

首先得明确:你遇到的404根本不是@RequestMapping嵌套的问题,而是请求参数的传递方式和接口定义不匹配导致的。

你当前的@DeleteMapping("/delete/{id}")定义的是路径变量(PathVariable),也就是说Spring只会匹配/delete/12这种把id放在URL路径里的请求;而/delete/?id=12是把id作为**查询参数(RequestParam)**传递的,和当前的接口映射规则完全不搭,自然会返回404。

能不能用application.properties解决?

答案是不能。这是Spring MVC请求映射的核心规则,不属于可通过配置文件修改的范畴,application.properties里没有相关配置项能让PathVariable自动适配查询参数的写法。

正确的解决方式

你有两种选择,根据你的需求来:

1. 修改接口为支持查询参数(适配/delete/?id=12)

把方法的参数注解改成@RequestParam,同时调整@DeleteMapping的路径:

@DeleteMapping(value = "/delete")
public void deleteComment(@RequestParam("id") long targetId) {
    commentService.removeComment(targetId);
}

这样发送http://localhost:8081/api/comment/delete?id=12(注意去掉路径里delete后的额外斜杠)就能成功匹配。

2. 同时支持路径变量和查询参数两种方式

如果想让两种URL都能触发这个接口,可以在方法里同时接收两种参数,并处理优先级:

@DeleteMapping(value = {"/delete/{id}", "/delete"})
public void deleteComment(@PathVariable(required = false) Long id, 
                          @RequestParam(required = false) Long targetId) {
    // 优先取路径变量的id,没有的话用查询参数的targetId
    long finalId = id != null ? id : targetId;
    commentService.removeComment(finalId);
}

这样不管是/delete/12还是/delete?id=12都能正常调用。

内容的提问来源于stack exchange,提问作者LeperAffinity666

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 01:54:22