Skip to content

Bind list or array to form in Thymleaf

On my website I have a few checkboxes each of them contains id in value attribute. After submitting form I’d like to have a list containing ids of checked checkboxes to be passed to the controller. That’s how I want to make new page comparing n products.

Controller can accept List<Long> or long[]. That’s what I have for now:


<form th:action="@{/comparison}" th:object="${productsComparison}" target="_blank" method="post">
  <tr data-th-each="item, iter : ${items.item}">
      <input type="checkbox" th:name="|productsComparison.ids[${iter.index}]|" th:value="${}"/>

I’ve added to my controller List<Long> wrapped in ProductComparison with appropriate getters and setters. After submitting form list is always null.


public String showProducts(Model model) {
    ProductsComparison productsComparison = new ProductsComparison();
    model.addAttribute("productsComparison", productsComparison);

public String compareProducts(@ModelAttribute ProductsComparison productsComparison) {
    System.out.println("List: " + productComparison.getIds());
    // Always shows null
    return "comparison";
public class ProductsComparison {
    private List<Long> ids;
    // Getters & setters



I’ve finally found solution. Instead of th:name I had to use th:field.


Because it’s field I didn’t have to specify object productsComparison before ids. ids field is List<String>.

To be honest I have no idea what underscores do, I will be glad if someone could explain.

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