Spring+Thymeleaf:如何将Map作为表单支持Bean绑定输入框?
解决Thymeleaf绑定HashMap键值到表单输入框的问题
先确认你的控制器代码(基础实现示例):
@Controller public class TestController { @ModelAttribute("test") public Map<String, String> initTestMap() { Map<String, String> testMap = new HashMap<>(); testMap.put("foo", "bar"); return testMap; } @GetMapping("/") public String showForm() { return "form"; } @PostMapping("/") public String submitForm(@ModelAttribute("test") Map<String, String> testMap) { // 处理提交后的Map数据 return "result"; } }
可行实现方式
方法一:不使用th:object,直接绑定模型中的Map
这种写法最直接,跳过对象绑定,直接通过模型变量访问Map的键:
<form th:action="@{/}" method="post"> <input type="text" th:field="${test['foo']}"> <button type="submit">提交</button> </form>
方法二:使用th:object访问Map
如果一定要绑定th:object="${test}",需要用Thymeleaf针对Map的特殊访问语法,直接通过数组式键名访问,不要用JavaBean属性的写法:
<form th:object="${test}" th:action="@{/}" method="post"> <input type="text" th:field="*{['foo']}"> <button type="submit">提交</button> </form>
之前写法报错的原因
*{foo}:Thymeleaf会按照JavaBean规则尝试调用HashMap的getFoo()方法,但HashMap没有这个方法,因此触发属性不存在的错误。*{#object['foo']}:在*{...}表达式中不需要显式写#object,这种写法冗余且不符合Thymeleaf的表达式规则,导致解析错误。
内容的提问来源于stack exchange,提问作者YoavKlein
相关产品推荐
相关产品推荐

