springmvc使用的是Hibernate Validator(和Hibernate的ORM无关)来完成校验功能
1.导入jar包
2.编写校验错误配置文件
3.配置校验错误信息文件
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <!-- 资源文件名,这里property的name为basenames所以错误信息的配置文件CustomValidationMessages省去后缀 --> <property name="basenames"> <list> <value>classpath:ItemValidationMessages</value> </list> </property> <!-- 资源文件编码格式 --> <property name="fileEncodings" value="UTF-8" /> <property name="defaultEncoding" value="UTF-8"/> <!-- 对资源文件内容缓存时间,单位秒 --> <property name="cacheSeconds" value="120" /> </bean>
4.配置校验器
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <!-- 指定校验器提供方 --> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> <!-- 指定校验使用的资源文件,如果不指定默认使用classpath下的ValidationMessages.properties --> <property name="validationMessageSource" ref="messageSource"/> </bean>
5.将校验器注入到适配器中
<!-- 使用<mvc:annotation-driven>可以代替单个配置注解映射器和注解适配器 ,它默认加载很多参数绑定方法 比如json转换解析器就默认加载了,实际开发用这个 validator="":校验器注入到适配器中--> <!-- 默认的注解映射的支持 --> <mvc:annotation-driven validator="validator"></mvc:annotation-driven>
6.类属性中定义规则
@Size(min=1,max=30,message="{item.itemname.length.erro}",groups={ItemGroup1.class,ItemGroup2.class}) private String itemname; @NotNull(message="{item.price.isNULL}",groups={ItemGroup2.class}) private Double price;
7.在controller中处理数据错误
/*1.在需要校验的pojo前边添加注解@Validated,在需要校验的pojo后面添加BindingResult bindingResult接收校验出错信息 注意:@Validated和BindingResult bindingResult是配对出现的,并且形参顺序是固定的(一前一后) value={ItemGroup1.class}:指定使用ItemGroup1的分组校验*/ @RequestMapping("/editItemSubmit") public ModelAndView editItemSubmit(HttpServletRequest request,@Validated(value={ItemGroup1.class}) ItemCustom itemCustom, BindingResult bindingResult) throws Exception{ //如果有错误 if(bindingResult.hasErrors()) { //获取错误信息 List<ObjectError> allErrors = bindingResult.getAllErrors(); ModelAndView modelAndView = new ModelAndView(); //将错误信息传到jsp页面中 modelAndView.addObject("allErrors", allErrors); modelAndView.setViewName("item/editItem"); return modelAndView; }
itemService.updateItem(itemCustom);
ModelAndView modelAndView = new ModelAndView("redirect:/item/queryItems.action");
return modelAndView;
}