使用model.addAttribute()传递数据失效,提交后部分字段为null的问题
问题原因分析
问题核心在于表单提交时未将type和city字段的值传递回后端:
你在createRacunForm方法中把type和city设置到racun对象并通过model.addAttribute传到前端,前端能正常显示是因为直接读取了Model中的数据,但HTML表单默认只会提交表单控件(如input、textarea等)的参数。由于你没有把type和city作为表单的一部分提交,后端通过@ModelAttribute绑定对象时,这两个字段没有对应的请求参数,最终被设为null。
修复方案
方案1:在HTML表单中添加隐藏域
在racun_new.html的表单里,新增两个隐藏输入框,将type和city的值嵌入表单,提交时自动传递给后端:
<form th:action="@{/racun/new}" th:object="${racun}" method="post"> <!-- 原有输入框:price、description --> <input type="number" th:field="*{price}" placeholder="价格"/> <textarea th:field="*{description}" placeholder="描述"></textarea> <!-- 添加隐藏域传递type和city --> <input type="hidden" th:field="*{type}" /> <input type="hidden" th:field="*{city}" /> <button type="submit">保存</button> </form>
Thymeleaf的th:field会自动绑定racun对象的属性值,并生成正确的name属性,确保后端能通过@ModelAttribute正确接收。
方案2:通过请求参数重新传递值
如果不想使用隐藏域,可修改Post请求的参数接收逻辑,从请求参数中获取type和city后重新设置到racun对象:
第一步:修改Controller的Post方法
@PostMapping("/racun/new") public String createRacun(@ModelAttribute("racun") Racun racun, @RequestParam String type, @RequestParam String city){ racun.setType(type); racun.setCity(city); return racunService.createNewRacun(racun); }
第二步:前端表单拼接参数
在表单的action中携带type和city参数:
<form th:action="@{/racun/new(type=${racun.type}, city=${racun.city})}" th:object="${racun}" method="post"> <!-- 原有输入框 --> <button type="submit">保存</button> </form>
补充规范提醒
Java类名需遵循大驼峰规范,建议将racun类重命名为Racun,避免代码风格问题。
内容的提问来源于stack exchange,提问作者user13372981
相关产品推荐
相关产品推荐

