1、validator配置如下;
<mvc:annotation-driven conversion-service="conversionService" validator="validator"></mvc:annotation-driven>
<!--校驗器-->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
<property name="validationMessageSource" ref="messageSource"></property>
</bean>
<!--校驗錯誤信息配置文件-->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="message"></property>
<property name="cacheSeconds" value="120"></property>
<property name="fileEncodings" value="UTF-8"></property>
</bean>
2、添加註解;
@Size(min=1,max=20,message = "{fruits.name.length.error}")
private String name;
@NotEmpty(message = "{fruits.producing_area.isEmpty}")
private String producing_area;
3、自定義錯誤提示信息(properties配置文件下);
fruits.name.length.error=請輸入1到20個字符的商品名稱
fruits.producing_area.isEmpty=請輸入商品產地
4、在controller方法中添加@Validated和BindingResult註解(兩個需成對出現);
5、測試結果如下:(沒有輸出我們自定義的錯誤提示信息)
問題的解決:
大家一般都是用ReloadableResourceBundleMessageSource這個實現類,上面也是用這個實現類的;
但是上面就出現了這個問題,不知道大家會不會一樣有這個問題;
我的解決方法是將ReloadableResourceBundleMessageSource實現類改成ResourceBundleMessageSource實現類;但是會出現以下錯誤(ResourceBundleMessageSource實現類沒有fileEncodings的屬性);
此時將fileEncodings屬性改成defaultEncoding即可獲取到配置文件自定義的錯誤提示信息了;
出現以上問題和解決方法的原理其實我還不懂,並且這種方法還不一定對,所以有同學明白的話還請告知以下,謝謝。