javaspring-mvcthymeleaf

Spring+Thymeleaf - Map as form-backing bean


Supposing I have the following controller code:

    @ModelAttribute("test")
    public Map<String, String> test() {
        Map<String, String> someMap = new HashMap<>();
        someMap.put("foo", "bar");
        return someMap;
    }

Now, in my template, I want to have an input element which populates this foo key in the map. I tried:

<form th:object="${test}" th:action="@{/}">
   <input type="text" th:field="*{foo}">
</form>

and

<form th:object="${test}" th:action="@{/}">
   <input type="text" th:field="*{#object['foo']}">
</form>

and I get:

 Invalid property '#object[Kaki]' of bean class [java.util.HashMap]:

is that possible somehow?


Solution

  • Use a wrapper for your form class:

    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;
        }
    }
    

    And for your <form> itself, the th:field should look like this:

    <form th:object="${test}" th:action="@{/}" method="post">
       <input type="text" th:field="*{map['foo']}">
    </form>