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

Spring Boot中JSP表单按ID删除数据时ID为空的问题求助

问题分析
  1. 参数名不匹配:JSP表单中输入框的name属性是shoename,但Controller方法deleteById接收的参数是id,提交后参数以shoename=1的形式传递,导致id参数为null,最终传递给RestController时触发空指针异常。
  2. HTTP方法不符合规范:删除操作使用GET请求不符合REST设计原则,GET请求应仅用于查询,删除操作建议使用DELETE方法。
  3. 内部调用冗余:Controller层直接调用RestController的HTTP接口属于冗余设计,内部服务调用应直接依赖Service层,无需通过HTTP请求。
解决方案

1. 修正JSP表单参数名与提交方式

将输入框的name改为id,同时调整表单提交方式为POST并添加隐藏域指定请求方法为DELETE(HTML表单原生不支持DELETE,Spring Boot可通过_method参数转换请求方法):

<h3>To delete an Item:</h3>
<form action="deletebyid" method="post">
    Enter Shoe ID: <input type="text" name="id"><br>
    <input type="hidden" name="_method" value="DELETE">
    <button>Submit</button>
</form>

注:Spring Boot 2.x及以上默认开启HiddenHttpMethodFilter,若未开启可在配置类中添加:

@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
    return new HiddenHttpMethodFilter();
}

2. 修正Controller层逻辑

删除Controller中调用RestController的冗余代码,直接注入Service层执行删除操作,同时修正请求映射为DELETE方法:

@Controller
public class WareHouseController {

    @Autowired
    private ShoeService shoeService;

    @RequestMapping(value = "deletebyid", method = RequestMethod.DELETE)
    public String deleteById(@RequestParam Long id) {
        ShoeData data = shoeService.deleteById(id);
        return "redirect:/entry";
    }
}

3. 空指针防护优化

在接收参数的方法中添加非空校验,避免空指针异常:

@RequestMapping(value = "deletebyid", method = RequestMethod.DELETE)
public String deleteById(@RequestParam(required = true) Long id) {
    if(id == null) {
        return "error"; // 返回错误页面或提示
    }
    ShoeData data = shoeService.deleteById(id);
    return "redirect:/entry";
}

4. 保留RestController的API规范(可选)

如果RestController是对外提供的API,保持原有逻辑不变即可,内部Controller直接依赖Service层,无需调用该API:

@RestController
public class RestfulResource {

    @Autowired
    private ShoeService shoeService;

    @DeleteMapping(path = "shoelist/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        ShoeData data = shoeService.deleteById(id);
        return data != null ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:35:31