【问题标题】:Thymeleaf construct objectThymeleaf 构造对象
【发布时间】:2017-04-12 01:46:47
【问题描述】:

我将模型属性从控制器传递到 thymeleaf 形式,所以我可以像这样绑定对象:

<div class="container" style="max-width: 600px" th:fragment="signupForm">
    <form name="f" th:action="@{/signup}" th:object="${userCredentials}" method="post" class="form-horizontal">
        <input th:placeholder="#{messages.form.email}" type="text" th:field="*{email}"
               name="email" id="email" class="form-control"/>
        <input th:placeholder="#{messages.form.name}" type="text" th:field="*{name}"
               name="name" id="name" class="form-control"/>
        <input type="password" th:placeholder="#{messages.form.password}" th:field="*{password}"
               name="password" id="password"/>
        <button type="submit" th:text="#{messages.form.signup}"></button>
    </form>
</div>

但是我想将此表单作为其他视图的片段重用,但我不能这样做,因为${userCredentials} 表单对象未初始化。我可以像这样在我的视图中构造这个对象吗?

<div th:if="${userCredentials == null}" th:with="userCredentials=new UserCredentials()"></div>

【问题讨论】:

    标签: java spring thymeleaf


    【解决方案1】:

    我认为不可能使用new 创建对象,但是您可以在 UserCredentials 上创建一个返回新对象并使用它的静态方法。像这样的:

    public class UserCredentials {
      public static UserCredentials create() {
        return new UserCredentials();
      }
    }
    

    在百里香中

    <div th:if="${userCredentials == null}" th:with="userCredentials=${T(your.package.here.UserCredentials).create()}"></div>
    

    【讨论】:

      【解决方案2】:

      你可以在th:with中创建一个对象,使用

      th:with="userCredentials=${new UserCredentials()}"
      

      【讨论】:

        猜你喜欢
        • 2019-09-12
        • 1970-01-01
        • 1970-01-01
        • 2012-02-03
        • 2013-10-20
        • 2021-10-22
        • 2018-03-03
        • 2013-02-03
        • 1970-01-01
        相关资源
        最近更新 更多