spring引导thymelaf表单字段,该字段不是表单对象的一部分



我使用Spring Thymelaf只是出于简单的练习原因。我有一个自定义的个人类用于我的个人模式。这个Person类也包含一个散列密码字段。

为了添加一个新的Person,我有一个简单的表单,其中传递了Person类所需的属性。因此,我在模型中添加了以下内容:

Person newP = new Person();
model.addAttribute("personForm", newP);

并设置这样的html字段:

<form action="#" th:action="@{/persons}" th:object="${personForm}" method="post">

然而,我也想在表单中添加两个不包含在Person类中的额外字段:

  • 密码
  • 重复密码

这两个字段应在表单提交后进行验证。然后,我的Person类的密码散列字段应该用它来填充。这是在相应的Post RequestMapping的功能中处理的。

由于这两个字段没有在我的person类中定义,我想知道是否还有一种方法可以将这两个域包含到我的表单中,而不必将它们添加到我的person类中。

您可以创建PersonCreateDto其中包括Person实体和另外两个Felds

public class PersonCreateDto{
private Person person;
private String firstfeld;
private String secondfeld;
....
}
PersonCreateDto personCreateDto = new PersonCreateDto();
model.addAttribute("personCreateDto ", personCreateDto );
<form action="#" th:action="@{/persons}" th:object="${personCreateDto}" method="post">
<input th:type="text" name="firstName" id="firstName" th:field="*{personCreateDto.person.firstName}" class="form-control"></input>
<input th:type="text" name="firstfeld" id="firstfeld" th:field="*{personCreateDto.firstfeld}" class="form-control"></input>
<input th:type="text" name="secondfeld" id="secondfeld" th:field="*{personCreateDto.secondfeld}" class="form-control"></input>

最新更新