【问题标题】:Thymeleaf - How to send an object (with child object) from form back to the ControllerThymeleaf - 如何将对象(带有子对象)从表单发送回控制器
【发布时间】:2020-09-25 04:59:15
【问题描述】:

我正在尝试将“复杂”对象从百里香叶形式“发送”回控制器。 我找到了这个最小的例子(Send datas from html to controller in Thymeleaf?),它基本上做同样的事情(完美地工作)。唯一的区别是,它们的对象具有 String 属性而不是其他对象。

但是,一旦我用 bar 对象替换了 String 属性,在提交表单时,bar 对象始终为空。 甚至可以提交嵌套对象吗?

对象

public class Foo {
    private Bar bar;

    public Bar getBar() {
        return bar;
    }

    public void setBar(Bar bar) {
        this.bar = bar;
    }
}

public class Bar {

    private String id;

    public Bar(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

控制器

@RequestMapping(value = "/showForm", method= RequestMethod.GET)
public String showForm(Model model) {
    Foo foo = new Foo();
    foo.setBar(new Bar("test"));
    model.addAttribute("foo", foo);
    return Pages.TEST;
}

@RequestMapping(value = "/processForm", method=RequestMethod.POST)
public String processForm(@ModelAttribute(value="foo") Foo foo) {
    ...
    return Pages.TEST;
}

HTML

<form action="#" th:action="@{/processForm}" th:object="${foo}" method="post">
    <input type="text" th:field="*{bar}"/>
    <input type="submit"/>
</form>

【问题讨论】:

    标签: forms spring-boot thymeleaf


    【解决方案1】:

    您必须将输入文本绑定到 bar 对象的 id 字段。

    <form action="#" th:action="@{/processForm}" th:object="${foo}" method="post">
        <input type="text" th:field="*{bar.id}"/>
        <input type="submit"/>
    </form>
    

    【讨论】:

    • bar 对象中缺少 id 字段的绑定是一个问题。另一个是 Bar.class 中的构造函数。其中,绑定 'id' 后导致此异常:NullValueInNestedPathException: Invalid property 'bar' of bean class [Foo]: Could not instantiate property type [Bar] to auto-grow nested property path; nested exception is java.lang.NoSuchMethodException: Bar.&lt;init&gt;()) 在向 Bar.class 添加默认构造函数后,它起作用了。
    猜你喜欢
    • 2019-09-29
    • 1970-01-01
    • 2015-09-04
    • 2020-10-19
    • 2016-08-05
    • 2019-05-20
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多