zoukankan      html  css  js  c++  java
  • SpringMVC的数据校验

    一、数据校验

     SpringMVC的校验指的是服务端的校验。
     通常使用较多的是前端页面的js校验,但是对于安全度要求高的数据建议在服务端进行数据校验。
     在SpringMVC的Controller中校验页面请求的参数的合法性。service中主要校验业务参数,仅限于service接口中使用的参数,在dao层一般不进行数据的校验。

    二、SpringMVC的校验

    1、校验依赖

      SpringMVC使用hibernate的校验框架validation进行数据的校验,该校验框架可hibernate没有任何关系。在校验时需要加入如下的jar包。

    2、校验器的配置

      示例:校验商品名称长度不能超过30个字符,价格不能为空.
     第一步:在SpringMVC的配置文件中配置校验器。

       <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
            <!--hibernate校验器-->
            <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
            <!--指定校验的资源文件,在文件中配置校验错误时的提示信息,如果不配置,
                默认使用classpath下的ValidationMessage.propeties文件
            -->
            <property name="validationMessageSource" ref="messageSource"/>
        </bean>
    

     第二步:在在SpringMVC的配置文件中配置校验器资源文件

     <!--配置校验的错误文件-->
        <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
            <!--资源文件名称-->
            <property name="basenames">
                <list>
                    <value>classpath:config/itemsValidationMessage</value>
                </list>
            </property>
            <!--资源文件编码格式-->
            <property name="fileEncodings" value="utf-8"/>
            <!--资源文件缓存时间-->
            <property name="cacheSeconds" value="120"/>
        </bean>
    

     第三步:在pojo中添加注解

     @Size(max = 30,message = "{items.name.max}")
        private String name;
    
        @NotNull(message = "{items.price.null}")
        private Float price;
    

     第四步:编写校验器的资源文件

    items.name.max =名称字符不能超过30个字
    items.price.null =价格不能为空
    

     第五步:在controller中接受错误信息

      /**
         *在需要校验的pojo前边添加@Validated,在需要校验的pojo后边添加BindingResult bindingResult接收校验出错信息
         注意:@Validated和BindingResult bindingResult是配对出现,并且形参顺序是固定的(一前一后)。
         * @param bindingResult 校验出错信息
         */
        @RequestMapping("/updateitems")
        public String updateitems(Model model,Integer id, @Validated ItemsCustom itemsExtend,
                                  BindingResult bindingResult) throws Exception{
    
            if(bindingResult.hasErrors()){
                List<ObjectError> errors = bindingResult.getAllErrors();
                for (ObjectError error: errors) {
                    System.out.println(error.getDefaultMessage());
                }
                model.addAttribute("errors",errors);
                model.addAttribute("itemsExtend",itemsExtend);
                return "updateitem";
            }
                itemsService.updateitems(id,itemsExtend);
            return"redirect:queryItems.action";
        }
    

     第六步:在页面中展示错误信息

     <c:if test="${errors != null }">
                <c:forEach items="${errors}" var="error">
                   <font color="red"> ${error.defaultMessage}</font>
                </c:forEach>
            </c:if>
    

    3、测试结果

    三、分组校验

    1、使用分组校验的原因

    在pojo中定义校验规则,而pojo是被多个 controller所共用,当不同的controller方法对同一个pojo进行校验,但是每个controller方法需要不同的校验。

    2、解决方法###

    定义多个校验分组(其实是一个java接口),分组中定义有哪些规则
    每个controller方法使用不同的校验分组。

    3、分组校验实现

    (1)定义校验分组,创建两个分组的接口,接口中不需要任何方法。

    //校验分组1  
    public interface VaildatorGroup1 {
    }
    
    //校验分组2  
    public interface VaildatorGroup2 {
    }
    

    (2)在pojo的校验注解中添加分组

    /**
         * max:最大值
         * mesage:出错提示信息
         * group:校验分组
         */
        
        @Size(max = 30,message = "{items.name.max}",groups = {VaildatorGroup1.class})
        private String name;
    
        @NotNull(message = "{items.price.null}" ,groups = {VaildatorGroup1.class,ValidatorGroup2.class})
        private Float price;
    

    (3)在Controller中指定要校验的分组。

       /**
         *在需要校验的pojo前边添加@Validated,在需要校验的pojo后边添加BindingResult bindingResult接收校验出错信息
         注意:@Validated和BindingResult bindingResult是配对出现,并且形参顺序是固定的(一前一后)。
         * @param bindingResult 校验出错信息
         */
        @RequestMapping("/updateitems")
        public String updateitems(Model model,Integer id, @Validated(value = {VaildatorGroup1.class}) ItemsCustom itemsExtend,
                                  BindingResult bindingResult) throws Exception{
    
            if(bindingResult.hasErrors()){
                List<ObjectError> errors = bindingResult.getAllErrors();
                for (ObjectError error: errors) {
                    System.out.println(error.getDefaultMessage());
                }
                model.addAttribute("errors",errors);
                model.addAttribute("itemsExtend",itemsExtend);
                return "updateitem";
            }
                itemsService.updateitems(id,itemsExtend);
            return"redirect:queryItems.action";
        }
    

    四 校验规则说明

    @Null 被注释的元素必须为 null
    @NotNull 被注释的元素必须不为 null
    @AssertTrue 被注释的元素必须为 true
    @AssertFalse 被注释的元素必须为 false
    @Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
    @Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
    @DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
    @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
    @Size(max=, min=) 被注释的元素的大小必须在指定的范围内
    @Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
    @Past 被注释的元素必须是一个过去的日期
    @Future 被注释的元素必须是一个将来的日期
    @Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
    Hibernate Validator 附加的 constraint
    @NotBlank(message =) 验证字符串非null,且长度必须大于0
    @Email 被注释的元素必须是电子邮箱地址
    @Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
    @NotEmpty 被注释的字符串的必须非空
    @Range(min=,max=,message=) 被注释的元素必须在合适的范围内

  • 相关阅读:
    URL传递的参数是UTF-8编码,在打开的页面正常显示(GB2312)的方法
    JS windows.open打开窗口并居中
    一个tomcat如何部署多个项目运行
    redis 服务配置开机自启动
    解决端口被占用问题
    MySQL中concat以及group_concat的使用
    java 使用OpenOffice文件实现预览
    eclipse安装maven插件
    数据库三范式
    mysql 查询的字段值太长显示不全 group_concat
  • 原文地址:https://www.cnblogs.com/jack1995/p/7357573.html
Copyright © 2011-2022 走看看