希望这会有所帮助。来源是:Mastering Spring MVC
您需要添加更多内容才能使验证生效。首先,控制器需要说它想要一个有效的表单提交模型。添加javax.validation.Valid 以及
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
对代表表单的参数的注释就是这样做的:
@RequestMapping(value = "/profile", method = RequestMethod.POST)
public String saveProfile(@Valid ProfileForm profileForm,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "profile/profilePage";
}
System.out.println("save ok" + profileForm);
return "redirect:/profile";
}
请注意,如果表单包含任何错误,您不会重定向用户。这将允许您在同一网页上显示它们。说到这一点,您需要在网页上添加一个显示这些错误的位置。
在profilePage.html 中添加这些行:
<form th:action="@{/profile}" th:object="${profileForm}"
....">
<div class="row">
<div class="input-field col s6">
<input th:field="${profileForm.twitterHandle}"
id="twitterHandle" type="text" th:errorclass="invalid"/>
<label for="twitterHandle">Twitter handle</label>
<div th:errors="*{twitterHandle}" class="redtext">
Error</div>
</div>
<div class="input-field col s6">
<input th:field="${profileForm.email}" id="email"
type="text" th:errorclass="invalid"/>
<label for="email">Email</label>
<div th:errors="*{email}" class="red-text">Error</div>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input th:field="${profileForm.birthDate}"
id="birthDate" type="text" th:errorclass="invalid" th:placeholder="${
dateFormat}"/>
<label for="birthDate">Birth Date</label>
<div th:errors="*{birthDate}" class="red-text">Error</
div>
</div>
</div>
<div class="row s12">
<button class="btn indigo waves-effect waves-light"
type="submit" name="save">Submit
<i class="mdi-content-send right"></i>
</button>
</div>
</form>
是的,确实, Spring Boot 负责为我们创建一个消息源 bean。
此消息源的默认位置在
src/main/resources/messages.
properties.
创建这样一个包,并添加以下文本:
Size.profileForm.twitterHandle=Please type in your twitter user name
Email.profileForm.email=Please specify a valid email address
NotEmpty.profileForm.email=Please specify your email address
PastLocalDate.profileForm.birthDate=Please specify a real birth date
NotNull.profileForm.birthDate=Please specify your birth date
typeMismatch.birthDate = Invalid birth date format
。