我将模型属性从 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/