java - Thymeleaf 构造对象

标签 java spring thymeleaf

我将模型属性从 Controller 传递到 thymeleaf 表单,这样我就可以像这样绑定(bind)对象:

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

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

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

最佳答案

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

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

在 thymeleaf

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

关于java - Thymeleaf 构造对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40842588/

相关文章:

java - 仅按下第一个键时如何执行操作?

java - 如何连接到eureka中的应用程序实例?

java - 无法使用路径映射 Controller

java - 如何管理由于发布请求和历史记录而产生的 session 属性

java - Thymeleaf:将输入文本作为表单操作中的参数传递

java - 如何在 Selenium 中切换

java - 如何在 spring batch 的 FlatFileReader 中设置分隔符值?

java - Spring错误-线程中的异常 "main"java.lang.ExceptionInInitializerError

spring - 我们可以以 thymeleaf 形式发布 JWT token 吗

java - 将属性传递给 GWT 服务器的最佳方式