Thymeleaf provide null in controller

Viewed 154

I want to deliver the entire object from html to the controller

Controller:

@RequestMapping(method = RequestMethod.GET)
public String get(){
    Info info = new Info();
    info.setTitle("Hello");
    model.addAttribute("infos", Collections.singleton(info));
    return "info-page";
}
@RequestMapping(method = RequestMethod.POST, value = "show-all")
public String showAllInfoObject(@ModelAttribute("info") Info info){
    // info has null values!
}

HTML

<li th:each="info : ${infos}">
    <span th:text="${info.title}">webTitle</span>.
    <form th:action="@{'/show-all}" method="post">
        <input type="hidden" name="result" th:field="*{info}" />
        <input type="submit" value="show detalis" />
    </form>
</li>

However, the controller gets an empty object. Interestingly, when I provide only String "title", it gets the correct result in the controller.

How to deliver correctly the whole object from HTML?

1 Answers

The problem is that th:field replaces the attributes value, id, and name in the input tag.

I would rewrite the HTML code as something like this:

<ul>
    <li th:each="info : ${infos}">
        <span th:text="${info.title}"></span>
        <form th:action="@{/show-all}" method="post"   >
            <input type="hidden" th:value="${info.title}" name="title" id="title" />
            <input type="submit" value="show detalis" />
        </form>
    </li>
</ul>

So, setting the input name and id with "title", the controller will make the bind as expected.

The controller code remains the same but I will leave here the test that I did.

    @RequestMapping(method = RequestMethod.GET)
    public String get(Model model){
        Info info = new Info();
        info.setTitle("Hello");
        Info info2 = new Info();
        info2.setTitle("Hello2");
        model.addAttribute("infos", Arrays.asList(info, info2));
        return "info-page";
    }

    @RequestMapping(method = RequestMethod.POST, value = "show-all")
    public String showAllInfoObject(@ModelAttribute("info") Info info){
        // info has values!
        return "info-page";
    }

Hope it helps you.

Related