• JSR303参数校验与全局异常处理


    1、导入依赖

    
       org.springframework.boot
        spring-boot-starter-validation
    
    
    • 1
    • 2
    • 3
    • 4

    2、全局异常处理

    package com.itheima.config;
    import com.itheima.domain.JSONResult;
    import org.springframework.validation.BindException;
    import org.springframework.web.bind.MethodArgumentNotValidException;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RestControllerAdvice;
    import javax.validation.ConstraintViolation;
    import javax.validation.ConstraintViolationException;
    import java.util.Set;
    /**
     * @author: XuXin
     * @date: 2023/9/21
     */
    @RestControllerAdvice
    public class GlobalExceptionHandler {
        @ExceptionHandler(Exception.class)
        public JSONResult exceptionHandler(Exception e) {
            return new JSONResult(02, null, null);
        }
        @ExceptionHandler(BindException.class)
        public JSONResult bindExceptionHandler(BindException e) {
            String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
            return new JSONResult(9999, null, message);
        }
        @ExceptionHandler(ConstraintViolationException.class)
        public JSONResult constraintViolationExceptionHandle(ConstraintViolationException e) {
            JSONResult jsonResult = new JSONResult();
            Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
            constraintViolations.forEach(item -> {
                jsonResult.setMsg(item.getMessage());
            });
            return jsonResult;
        }
        @ExceptionHandler(MethodArgumentNotValidException.class)
        public JSONResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
            JSONResult jsonResult = new JSONResult();
            e.getBindingResult().getFieldErrors().forEach(field -> {
                jsonResult.setMsg(field.getDefaultMessage());
            });
            return jsonResult;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    3、快速校验配置

    package com.itheima.config;
    import org.hibernate.validator.HibernateValidator;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import javax.validation.Validation;
    import javax.validation.Validator;
    import javax.validation.ValidatorFactory;
    /**
     * @author: XuXin
     * @date: 2023/9/21
     */
    @Configuration
    public class ValidatorConfiguration {
        @Bean
        public Validator validator(){
            ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
                    .configure()
                    .addProperty( "hibernate.validator.fail_fast", "true" )
                    .buildValidatorFactory();
            Validator validator = validatorFactory.getValidator();
            return validator;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    返回定义JSONResult

    package com.itheima.domain;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    /**
     * @author: XuXin
     * @date: 2023/9/21
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class JSONResult {
        private Integer state;
        private Object data;
        private String msg;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    实体类

    package com.itheima.domain;
    import lombok.Data;
    import org.springframework.stereotype.Component;
    import javax.validation.constraints.NotBlank;
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Null;
    import java.io.Serializable;
    /**
     * @Author CandyWall
     * @Date 2022/1/19--22:58
     * @Description
     */
    @Component
    @Data
    public class Book implements Serializable {
        private Integer id;
        @NotBlank(message = "书名不可为空")
        private String name;
        private String type;
        private String description;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    package com.itheima.domain;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.Getter;
    import lombok.NoArgsConstructor;
    import org.hibernate.validator.constraints.Length;
    import org.hibernate.validator.constraints.Range;
    import javax.validation.Valid;
    import javax.validation.constraints.*;
    import java.util.Date;
    /**
     * @author: XuXin
     * @date: 2023/9/21
     */
    @Data
    public class ValidationDemo {
        private Integer id;
        @Length(min = 4, max = 8, message = "用户名长度要求在{min}-{max}之间")
        @NotNull(message = "用户名不可为空")
        private String username;
        @Email(message = "邮箱格式错误")
        private String email;
        @Past(message = "出生日期错误")
        private Date birthday;
        @Min(value = 18, message = "未成年不满足注册要求")
        @Max(value = 80, message = "年龄错误")
        private Integer age;
        @Range(min = 0, max = 1, message = "性别选择错误")
        private Integer sex;
        @Valid
        @NotNull(message = "不可为空")
        private Book book;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    测试

    package com.itheima.controller;
    import com.itheima.domain.JSONResult;
    import com.itheima.domain.ValidationDemo;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.*;
    import javax.validation.Valid;
    import javax.validation.constraints.NotBlank;
    import javax.validation.constraints.NotNull;
    /**
     * @author: XuXin
     * @date: 2023/9/21
     */
    @RestController
    @Validated
    public class ValidationController {
        /**
         * @param demo          待校验实体
         * @param
         * @return
         * @Valid 表示对该实体进行校验
         */
        @RequestMapping(value = "validation", method = RequestMethod.POST)
        public JSONResult validate( @Validated @RequestBody ValidationDemo demo) {
            JSONResult jsonResult = new JSONResult();
            jsonResult.setState(11111);
            jsonResult.setData("校验成功");
            jsonResult.setMsg("");
            return jsonResult;
        }
        @GetMapping("/books")
        public JSONResult listParamForJson(@NotBlank(message = "不能为空且size大于0") String name) {
            JSONResult jsonResult = new JSONResult();
            jsonResult.setState(11111);
            jsonResult.setData("校验成功");
            jsonResult.setMsg("");
            return jsonResult;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    在这里插入图片描述
    在这里插入图片描述
    注意:

    • 如果方法参数只是对象形参,只需要在对象形参前面加上@Validated或@Valid注解来开启校验,类上不需要加上@Validated,对象里面的属性具体校验规则用@NotNull等注解,有嵌套验证时只需要在内嵌对象属性前面加上@Valid。
    • 如果方法参数只是普通形参,需要在类上加上@Validated注解来开启校验,参数具体校验规则用@NotNull等注解。
    • 如果方法参数既有对象形参也有普通形参,需要在对象形参前面加上@Validated或@Valid注解,也需要在类上需要加上@Validated来开启校验。对象里面的属性具体校验规则用@NotNull等注解,有嵌套验证时只需要在内嵌对象属性前面加上@Valid,普通参数具体校验规则用@NotNull等注解。
  • 相关阅读:
    2021 Domain Adaptation(李宏毅
    ES定期清理索引
    状态机动态规划之股票问题总结
    Nacos介绍以及使用
    Immutable是什么?
    WPF控件3
    《golang设计模式》第二部分·结构型模式-04-装饰器模式(Decorator)
    WSL + Docker容器,Windows上最爽的开发体验
    “2022年度科技行业CEO”!
    油气田勘探数字化转型现状及展望
  • 原文地址:https://blog.csdn.net/qq_41428418/article/details/133133035