今天在使用JSR-303 validation進行校驗時出現(xiàn)了標(biāo)題中的相關(guān)問題
po類相關(guān)代碼:
@Size(min=1,max=30,message="{items.name.length.error}")
private String name;
@NotNull(message="{items.createtime.isNUll}")
private Date createtime;
springmvc.xml:
<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
<!-- 校驗器 -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<property name="validationMessageSource" ref="messageSource" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:CustomValidationMessages</value>
</list>
</property>
<property name="fileEncodings" value="utf-8" />
<property name="cacheSeconds" value="120" />
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<property name="validationMessageSource" ref="messageSource" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:CustomValidationMessages</value>
</list>
</property>
<property name="fileEncodings" value="utf-8" />
<property name="cacheSeconds" value="120" />
</bean>
controller.java:
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model, HttpServletRequest request, Integer id, @Validated ItemsCustom itemsCustom, BindingResult bindingResult) throws Exception {
if (bindingResult.hasErrors()) {
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError objectError : allErrors) {
System.out.println(objectError.getDefaultMessage());
}
model.addAttribute("allErrors", allErrors);
model.addAttribute("items", itemsCustom);
return "items/editItems";
}
CustomValidationMessage.properties:
items.name.length.error=請輸入1到30個字符的商品名稱
items.createtime.isNULL=請輸入商品的生產(chǎn)日期
第一個問題很明顯是properties文件中的信息未正確加載導(dǎo)致的。經(jīng)檢查發(fā)現(xiàn)po類中非空校驗的代號為items.createtime.isNUll,properties文件中為items.createtime.isNULL,二者不匹配導(dǎo)致了錯誤。
另附springmvc加載配置properties文件的幾種方式以供學(xué)習(xí)http://blog.csdn.net/chinadim/article/details/40621671
第二個問題是由于編碼問題導(dǎo)致的
經(jīng)查詢將springmvc.xml文件中的
<property name="fileEncodings" value="utf-8" />
更改為:
<property name="defaultEncoding" value="utf-8" />
或者利用jdk根目錄bin文件夾下的native2ascii.exe文件將properties文件轉(zhuǎn)為UTF-8也可解決。