Using thymeleaf to post form data to a Controller that uses @ModelAttribute (complex objects)

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-29 04:16:16

问题


There is the Element class:

public class Element {

    private Long id;
    private Name name;

    // Getters and Setters ...
}

And the Name class:

public class Name {

    private String en;
    private String fr;
    private String de;

    // Getters and Setters ...
}

There is a getElementsController:

@GetMapping("/elements/create")
public String getElementsCreate() {
    return "private/new-element";
}

There is a NewElementController controller:

 @PostMapping("/elements/create")
    public String postElementsCreate(@ModelAttribute Element element) {

        System.out.println(element)
        return null;
}

There is a form that posts data to the NewElementController:

<form method="post" th:object="${element}" th:action="@{/elements/create}">
    <input type="text" value="1" name="id" placeholder="Id"/>
    // How should I make the input fields for: 
       element.name.en ?
       element.name.fr ?
       element.name.de ?
    <button type="submit">Save element</button>
</form>

Setting the Id works, but I can not access the name field (it is an object)
I have tried with th:field="*{name}" and with th:field="*{name.en}", but it does not work in that way.


回答1:


Try following:

<form method="post" th:object="${element}" th:action="@{/elements/create}">
    <input type="text" name="id" th:value="*{id}" placeholder="Id"/>
    <input type="text" name="name.en" th:value="*{name.en}" placeholder="Name (EN)"/>
    <input type="text" name="name.fr" th:value="*{name.fr}" placeholder="Name (FR)"/>
    <input type="text" name="name.de" th:value="*{name.de}" placeholder="Name (DE)"/>
    <button type="submit">Save element</button>
</form>

Yor controller method for GET should be like this:

@GetMapping("/elements/create")
public String getElementsCreate(Model model) {
    Element element = new Element();
    Name name = new Name();
    element.setName(name);
    model.addAttribute("element", element);
    return "private/new-element.html";
}


来源:https://stackoverflow.com/questions/42192373/using-thymeleaf-to-post-form-data-to-a-controller-that-uses-modelattribute-com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!