【SpringMVC】Validation校验
阅读原文时间:2022年05月22日阅读:1

2.1 引入 Hibernate Validator

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.4.1.Final</version>
</dependency>

2.2 配置

<!-- 校验器 -->
    <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>
    <!-- 校验错误信息配置文件 -->
    <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>



<!-- 自定义webBinder -->
    <bean id="customBinder"
        class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
        <!-- 使用converter进行参数转 -->
        <property name="conversionService" ref="conversionService" />
        <!-- 配置validator -->
        <property name="validator" ref="validator" />

        <!-- propertyEditorRegistrars用于属性编辑器 -->
        <!-- <property name="propertyEditorRegistrars"> <list> <ref bean="customPropertyEditor"
            /> </list> </property> -->
    </bean>


<!-- 注解适配器 -->
    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <!-- 在webBindingInitializer中注入自定义属性编辑器、自定义转换器 -->
        <property name="webBindingInitializer" ref="customBinder"></property>
        <!-- 加入 json数据的消息转换器 MappingJacksonHttpMessageConverter依赖Jackson的包 -->
        <property name="messageConverters">
            <list>
                <bean
                    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
            </list>
        </property>

    </bean>

2.3 创建CustomValidationMessages

  • 在classpath下创建CustomValidationMessages.properties

    校验提示信息:还需要在java中配置

    items.name.length.error=商品长度请限制在1-30之间items.createtime.is.notnull=请输入商品生产日期

2.4 校验规则

  • 商品信息提交时校验 ,商品生产日期不能为空,商品名称长度在1到30字符之间

    public class Items {
    private Integer id;

    //商品名称的长度请限制在1到30个字符
    @Size(min=1,max=30,message="{items.name.length.error}")
    private String name;
    
    private Float price;
    
    private String pic;
    
    //请输入商品生产日期
    @NotNull(message="{items.createtime.is.notnull}")
    private Date createtime;
    
    private String detail;

    }

2.5 捕获错误

  • 需要修改controller方法,在要校验的pojo前边加上@Validated,

    public String editItemSubmit(Model model,Integer id,
    @Validated @ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,
    BindingResult bindingResult,
    //上传图片
    MultipartFile pictureFile
    )throws Exception{

        //输出校验错误信息
        //如果参数绑定时有错
        //输出校验错误信息
        //如果参数绑定时有错
        if(bindingResult.hasErrors()){
        //获取错误
        List&lt;ObjectError&gt; errors = bindingResult.getAllErrors();
        //准备在页面输出errors,页面使用jstl遍历
        model.addAttribute("errors", errors);
        for(ObjectError error:errors){
            //输出错误信息
            System.out.println(error.getDefaultMessage());
        }
        //如果校验错误,回到商品修改页面
        return "editItem";
    }</code></pre>

    }

2.6 在页面上展示错误

<!-- 错误信息 -->
<c:forEach items="${errors }" var="error">
 ${error.defaultMessage }<br/>

</c:forEach>

2.7 分组校验

  • 需求

  • 针对不同的controller方法通过分组校验达到个性化校验的目的,修改商品修改功能,只校验生产日期不能为空。

  • 第一步:创建分组接口

    public interface ValidGroup1 {
    //接口不定义方法,就是只标识 哪些校验 规则属于该 ValidGroup1分组
    }

  • 第二步:定义校验规则属于哪个分组

    //请输入商品生产日期
    //通过groups指定此校验属于哪个分组,可以指定多个分组 @NotNull(message="{items.createtime.is.notnull}",groups={ValidGroup1.class})
    private Date createtime;

  • 第三步:在controller方法定义使用校验的分组

    public String editItemSubmit(Model model,Integer id,
    @Validated(value={ValidGroup1.class}) @ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,
    BindingResult bindingResult,
    //上传图片
    MultipartFile pictureFile
    )throws Exception{

    //...其他代码省略...

    }

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章