zoukankan      html  css  js  c++  java
  • (办公)springboot配置表单验证@Valid

      项目用到了springboot,本来很高兴,但是项目里什么东西都没有,验证,全局异常这些都需要自己区配置。最近springboot用的还是蛮多的,我还是做事情,把经验发表一下.

    SpringBoot提供了强大的表单验证功能实现,给我们省去了写验证的麻烦
    1.在传参类的属性上加注解
    @NotEmpty(message="姓名不能为空!")
    private String name;
    2.在controller层方法上,传参类加个@valid,并加个BindingResult 验证结果对象.
    
        public String method(@Valid 传参类 xxx,BindingResult bindingResult){
            if(bindingResult.hasErrors()){
                return bindingResult.getFieldError().getDefaultMessage();
            }
        
        }
            

       以下是常用的springboot表单验证的注解。

    限制    说明
    @Null     限制只能为null
    @NotNull     限制必须不为null
    @AssertFalse     限制必须为false
    @AssertTrue     限制必须为true
    @DecimalMax(value)     限制必须为一个不大于指定值的数字
    @DecimalMin(value)     限制必须为一个不小于指定值的数字
    @Digits(integer,fraction)     限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction
    @Future     限制必须是一个将来的日期
    @Max(value)     限制必须为一个不大于指定值的数字
    @Min(value)     限制必须为一个不小于指定值的数字
    @Past     限制必须是一个过去的日期
    @Pattern(value)     限制必须符合指定的正则表达式
    @Size(max,min)     限制字符长度必须在min到max之间
    @Past     验证注解的元素值(日期类型)比当前时间早
    @NotEmpty     验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
    @NotBlank     验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格
    @Email     验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

           另外还有一种返回方式:

    package com.lianrong.system.utils;
    import com.lianrong.system.bean.SystemCodeEntity;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    import javax.validation.ConstraintViolation;
    import javax.validation.Validation;
    import javax.validation.Validator;
    import javax.validation.groups.Default;
    
    public class ValidatorUtil {
        private static Validator validator = Validation.buildDefaultValidatorFactory()
                .getValidator();
    
        public static <T> Map<String,StringBuffer> validate(T obj){
            Map<String,StringBuffer> errorMap = null;
            Set<ConstraintViolation<T>> set = validator.validate(obj,Default.class);
            if(set != null && set.size() >0 ){
                errorMap = new HashMap<String,StringBuffer>();
                String property = null;
                for(ConstraintViolation<T> cv : set){
                    //这里循环获取错误信息,可以自定义格式
                    property = cv.getPropertyPath().toString();
                    if(errorMap.get(property) != null){
                        errorMap.get(property).append("," + cv.getMessage());
                    }else{
                        StringBuffer sb = new StringBuffer();
                        sb.append(cv.getMessage());
                        errorMap.put(property, sb);
                    }
                }
            }
            return errorMap;
        }
        /**
        public static void main(String[] args) {
            SystemCodeEntity systemCodeEntity = new SystemCodeEntity();
            print(ValidatorUtil.validate(systemCodeEntity));
        }*/
    
        public static StringBuffer print(Map<String,StringBuffer> errorMap){
            StringBuffer result = new StringBuffer("");
            if(errorMap != null){
                for(Map.Entry<String, StringBuffer> m : errorMap.entrySet()){
                    System.out.println(m.getKey() + ":" + m.getValue().toString());
                    result.append(m.getKey() + "" +m.getValue().toString()+",");
                }
            }
            return result;
        }
    }

        Controller的方法不用加@Valid,也不用传参数BindingResult

     StringBuffer resultMsg =  ValidatorUtil.print(
                    ValidatorUtil.validate(systemCodeVo)
            );
           if(resultMsg.length() > 0){
               return JsonData.error(resultMsg.toString());
           }

               提出一个小问题,增加不需要id,修改需要id,可以利用验证框架的分组功能groups

              

      public interface Default{}
        public interface Update{}
        /**
         * 编号.
         */
        @NotNull(message = "id不能为空",groups = Update.class)
        private Integer id;
    
        /**
         * 状态码
         */
        @NotBlank(message = "请输入状态码",groups = Default.class)
        private String type_code;
    @RequestMapping(value="/save",method = RequestMethod.POST)
        @ResponseBody
        public JsonData save(@RequestBody @Validated(value = Wordbookform.Default.class)
  • 相关阅读:
    swift优秀学习博客
    Swift主题色顶级解决方案一
    如何用 Swift 语言构建一个自定控件
    自定义UISlider的样式和滑块
    让你提前知道软件开发(27):创建数据库表和索引
    [6] 算法路
    OGG &quot;Loading data from file to Replicat&quot;table静态数据同步配置过程
    一些书籍和下载链接地址读研究生
    悖论软件测试农药
    Maven直接部署Web应用Tomcat
  • 原文地址:https://www.cnblogs.com/historylyt/p/10587913.html
Copyright © 2011-2022 走看看