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

Spring MVC表单提交后Problem类Priorytet字段仅存id其余属性为空问题

问题根因

你的表单中优先级下拉选择仅绑定了priorytet.id字段,提交时只会传递优先级ID到后端。Spring MVC的@ModelAttribute仅会根据请求参数填充对应属性,因此得到的Priorytet对象只有ID字段有值,其余属性默认是空。

解决方案

修改Controller的POST提交处理逻辑,接收到Problem对象后,根据传递的优先级ID从内存存储的priorytetList中查询完整的Priorytet对象,替换Problem中原有的不完整对象即可。
修改后的processForm方法代码如下:

@PostMapping(value = {"/add", "/edit/{problemId}"})
private String processForm(@ModelAttribute(name = "problem") Problem problem, Model model, @PathVariable(name="problemId", required=false) Integer id){
    // 新增逻辑:根据提交的优先级ID查询完整的优先级对象
    Long priorytetId = problem.getPriorytet().getId();
    Priorytet fullPriorytet = priorytetList.stream()
            .filter(p -> p.getId() == priorytetId)
            .findFirst()
            .orElseThrow(() -> new IllegalArgumentException("无效的优先级ID:" + priorytetId));
    problem.setPriorytet(fullPriorytet);

    // 原有逻辑保持不变
    if(id != null){
        lista.set((int) problem.getId(),problem);
    } else {
        problem.setId(lista.size());
        lista.add(problem);
    }

    model.addAttribute("problem", problem);
    return "successView";
}
注意事项
  • 必须先访问/wypelnij接口完成优先级和初始问题数据的初始化,否则查询优先级时会出现匹配不到或者空指针异常
  • 如果后续切换为数据库存储优先级数据,只需要把上面代码中遍历priorytetList的逻辑替换为DAO层根据ID查询优先级的方法即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:45:03