簡體   English   中英

Hibernate Validator無需使用Spring Framework即可檢索錯誤消息

[英]Hibernate Validator retrieve error messages without using Spring Framework

我目前正在使用hibernate-distribution-3.6.4.Final。 Hibernate Validator的新功能。

問題:如何檢索從向databean / formbean添加注釋中得到的錯誤消息? 我知道在春季,每個人似乎都在使用classpath中的messages.properties文件?

但是純休眠3怎么樣,是否有類似的文件,或者我應該怎么做? (在網上找不到好的答案...)

希望這會有所幫助。 來源是: 掌握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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM