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

Spring中使用void返回值实现ID删除,避免页面跳转的问题

问题解决思路

问题根源

你的控制器方法返回void,同时允许GET请求,Spring MVC会默认尝试根据请求路径/user_cart/remove/匹配渲染对应的视图模板(即templates/user_cart/remove.html),找不到该文件就会抛出你看到的错误。

解决方案

方案1:改用ResponseEntity返回无内容响应(推荐,符合REST规范)

将方法返回类型改为ResponseEntity<Void>,明确返回HTTP 204无内容状态码,这样Spring就不会去寻找视图模板:

@RequestMapping(value ="/user_cart/remove/", method = {RequestMethod.DELETE})
public ResponseEntity<Void> removeData(Long id) {
    userReqDetailService.removeByID(id);
    return ResponseEntity.noContent().build();
}

注:建议只保留DELETE方法,REST规范中GET用于查询,DELETE才是删除操作的标准方法,避免误触发删除逻辑。

方案2:添加@ResponseBody注解(若需保留GET方法)

如果必须保留GET方法,给方法加上@ResponseBody注解,告诉Spring直接返回响应体(无内容),不进行视图渲染:

@RequestMapping(value ="/user_cart/remove/", method = {RequestMethod.GET,RequestMethod.DELETE})
@ResponseBody
public void removeData(Long id) {
    userReqDetailService.removeByID(id);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:22:16