jar包

在springmvc.xml中配置validator
<!-- 配置注解驅動 -->
<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
<!-- 校驗器 -->
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- hibernate校驗器-->
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<!-- 指定校驗使用的資源檔案,在檔案中配置校驗錯誤資訊,如果不指定則預設使用classpath下的ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource" />
</bean>
<!-- 校驗錯誤資訊配置檔案 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 資源檔案名-->
<property name="basenames">
<list>
<value>classpath:LoginValidationMessages</value>
</list>
</property>
<property name="defaultEncoding" value="UTF-8"/>
<!-- 資源檔案編碼格式 -->
<property name="fileEncodings" value="utf-8" />
<!-- 對資源檔案内容緩存時間,機關秒 -->
<property name="cacheSeconds" value="120" />
</bean>
錯誤資訊的配置檔案LoginValidationMessages.properties
#添加校驗錯誤提示資訊
user.username.length.error=請輸入3到10字元的使用者名
user.password.length.error=請輸入5到20字元的密碼
user.email.error=請輸入正确的郵箱
controller
@RequestMapping(value="/login", method=RequestMethod.POST)
public String login(Model model,@Valid User user, BindingResult result) {
String page = "success";
if(result.hasErrors()){
page = "login";
List<ObjectError> list = result.getAllErrors();
model.addAttribute("errors", list);
} else{
model.addAttribute("user", user);
page = "success";
}
return page;
}
前端頁面顯示出錯資訊
<!-- 顯示出錯資訊 -->
<c:if test="${errors!=null}">
<c:forEach items="${errors}" var="error">
${error.defaultMessage }<br />
</c:forEach>
</c:if>
結果