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

求助:Spring MVC中<form:hidden>标签值为何为空?

问题分析与解决

核心原因

<form:hidden>值为空的根本原因是:MakeSwitchForm的custody字段未初始化、未赋值。

  • 控制器仅给custodyList赋值,但custody属性始终为null;
  • Spring表单标签(如<form:hidden>)优先从绑定的modelAttribute对象(即makeSwitchForm)中取path对应的属性值,而非value属性的EL表达式。由于custody是null,无法获取custody.custodyNumber,最终生成的字段值为空。

解决方案

方案一:控制器中初始化custody并赋值

修改控制器代码,在设置custodyList后,将列表第一个元素赋值给custody:

@GetMapping
public String defaultView(Model model, HttpServletRequest request, HttpServletResponse response, @RequestHeader(name = "Accept-Language") String locale)
        throws ServletException, IOException, PropertyValueNotFoundException, NoSuchMessageException  {
    MakeSwitchForm form = new MakeSwitchForm();
    List<Custody> custodyList = filterUserRightCustodies(redCustody, null);
    form.setCustodyList(custodyList);
    // 新增:为custody赋值
    if (custodyList != null && !custodyList.isEmpty()) {
        form.setCustody(custodyList.get(0));
    }
    model.addAttribute("makeSwitchForm", form);
    return "your-view-name"; // 补充视图返回语句
}

修改后,<form:hidden path="custody.custodyNumber"/>会自动从绑定的custody对象取值,无需再写value属性。

方案二:直接绑定列表元素(可选)

若无需绑定到custody属性,可直接使用列表元素的属性:

<form:hidden path="custodyList[0].custodyNumber"/>

此方式依赖<c:when>的判断(列表长度为1),确保custodyList[0]不为空。

补充说明

  • 普通<input>能正常显示是因为它直接通过EL表达式取值,不依赖Spring表单绑定;
  • 实体类的getter/setter正常,但必须保证对象已初始化并赋值,否则无法返回有效数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 21:29:57