Надеюсь, это поможет. Источник: Освоение 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 позаботится о создании исходного компонента сообщения для нас. Расположение по умолчанию для этого источника сообщений находится в
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
. ![введите здесь описание изображения](https://i.stack.imgur.com/B34Mg.png)
person
AchillesVan
schedule
23.07.2016