Skip to content
Advertisement

Recieve a Map from a HTML form with Thymeleaf

I’m working on a project with Spring Web and Thymeleaf (this is my first time using Thymeleaf) and I have this requirement:

The user needs to see a single form to fill a table with 32 rows and 4 columns, all at once.

Edit. Each row has a fixed key (just for clarification)

My first (naive) approach was to make inputs that look like this

    <th:block th:each="key:{keys}"
      <input th:name="|${key}Val1|" />
      <input th:name="|${key}Val2|" />
      <input th:name="|${key}Val3|" />
      <input th:name="|${key}Val4|" />
    </th:block>

This works well on the HTML side but, on the controller, I have a DTO with all 128 fields

    @PostMapping("/the/path")
    public void saveTable(Model model, @ModelAttribute TableDTO table){
        //ommited
    }
    public class TableDTO {
        private int key1Val1;
        private int key1Val2;
        private int key1Val3;
        private int key1Val4;
        private int key2Val1;
       // and so on for the 128 values
    }

This currently works, but I’m pretty sure there’s a better way.

Is there a way I can modify the bindings so I can receive something like this?

    @PostMapping("/the/path")
    public void saveTable(Model model, Map<Key, SimplerDTO> table){
        //ommited
    }

Where Key is an enum and SimplerDTO is a wrapper for the four values?

As said before, this is my first time with Thymeleaf, son any pointer will be well received.

Thanks in advance.

Advertisement

Answer

You can get all the post parameters in a single map by including an argument in your PostMapping function saveTable like:

@RequestParam Map<String, String> paramMap

That will have all 256 values for your use.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement