使用thymeleaf将表单数据发布到使用@ModelAttribute的Controller(复杂对象)

时间:2017-02-12 19:45:18

标签: spring spring-mvc thymeleaf

Element类:

public class Element {

    private Long id;
    private Name name;

    // Getters and Setters ...
}

Name类:

public class Name {

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

    // Getters and Setters ...
}

有一个getElementsController:

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

有一个NewElementController控制器:

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

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

有一个表单将数据发布到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>

设置ID有效,但我无法访问name字段(它是一个对象)
我尝试使用th:field="*{name}"th:field="*{name.en}",但它不能以这种方式工作。

1 个答案:

答案 0 :(得分:1)

请尝试以下操作:

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

GET的Yor控制器方法应该是这样的:

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