springMVC校验器(validator)

springmvc使用的是Hibernate Validator(和Hibernate的ORM无关)来完成校验功能

一.普通校验

  1.导入jar包

 

  2.编写校验错误配置文件

  3.配置校验错误信息文件 

     <bean id="messageSource"
              class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
            
            <property name="basenames">
                <list>
                    <value>classpath:ItemValidationMessagesvalue>
                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"/>
            
            <property name="validationMessageSource" ref="messageSource"/>
        bean>

 

  5.将校验器注入到适配器中

           
                
           <mvc:annotation-driven validator="validator">mvc:annotation-driven>    

  6.类属性中定义规则

    @Size(min=1,max=30,message="{item.itemname.length.erro}")
    private String itemname;
    
    @NotNull(message="{item.price.isNULL}")
    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 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;

  }

  8.测试

 

二.分组校验

    分组校验其实就是为了我们的校验更加灵活,有的时候,我们并不需要把我们当前配置的属性都进行校验,而需要的是当前的方法仅仅校验某些的属性。那么此时,我们就可以用到分组校验了...

  1.定义分组的接口【主要是标识】

    springMVC校验器(validator)_第1张图片

 

  2.定于校验规则属于哪一各组

        groups:指定此校验属性属于哪个分组(接口)

    @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;

   

  3.在Controller方法中定义使用校验分组

  红色部分:@Validated(value={ItemGroup1.class})
  @RequestMapping("/editItemSubmit")
    public ModelAndView editItemSubmit(HttpServletRequest request,
            @ModelAttribute("itemCustom") @Validated(value={ItemGroup1.class}) ItemCustom itemCustom, BindingResult bindingResult,MultipartFile item_pic) throws Exception{

你可能感兴趣的:(springMVC校验器(validator))