假设我有以下控制器代码:
@ModelAttribute("test")
public Map<String, String> test() {
Map<String, String> someMap = new HashMap<>();
someMap.put("foo", "bar");
return someMap;
}
现在,在我的模板中,我想要一个输入元素来填充地图中的这个
foo
键。我试过:
<form th:object="${test}" th:action="@{/}">
<input type="text" th:field="*{foo}">
</form>
和
<form th:object="${test}" th:action="@{/}">
<input type="text" th:field="*{#object['foo']}">
</form>
我得到:
Invalid property '#object[Kaki]' of bean class [java.util.HashMap]:
这有可能吗?
为您的表单类使用包装器:
public class MapForm {
private Map<String, String> map = new HashMap<>();
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
}
对于您的
<form>
本身,th:field
应该如下所示:
<form th:object="${test}" th:action="@{/}" method="post">
<input type="text" th:field="*{map['foo']}">
</form>