javax.validation参数校验

1、pom.xml文件中先引入一下依赖

<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>2.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.2.0.Final</version>
    </dependency>

2、常用的注解

@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提供的校验注解:  
@NotBlank(message =)   验证字符串非null,且trim后长度必须大于0    
@Email  被注释的元素必须是电子邮箱地址    
@Length(min=,max=)  被注释的字符串的大小必须在指定的范围内    
@NotEmpty   被注释的字符串的必须非空    
@Range(min=,max=,message=)  被注释的元素必须在合适的范围内

@AssertFalse 校验false  
@AssertTrue 校验true  
@DecimalMax(value=,inclusive=) 小于等于value,  
inclusive=true,是小于等于  
@DecimalMin(value=,inclusive=) 与上类似  
@Max(value=) 小于等于value  
@Min(value=) 大于等于value  
@NotNull  检查Null  
@Past  检查日期  
@Pattern(regex=,flag=)  正则  
@Size(min=, max=)  字符串,集合,map限制大小  
@Valid 对po实体类进行校验


如需其他注解,请参考hibernate validator官方文档了解其他验证约束注解和进行自定义的验证约束注解定义。

3、项目中引用

  首先在需要验证的实体类前添加注解 @Valid

   @PostMapping("admin/category/add")
    @ResponseBody
    public ApiRestResponse addCategory(HttpSession session,
        @Valid @RequestBody AddCategoryReq addCategoryReq) {
        
        User user=(User)session.getAttribute(Constant.IMOOC_MALL_USER);
        if(user == null) {
            return ApiRestResponse.error(ImoocMallExceptionEnum.NEED_LOGIN);
        }
        
        boolean checkAdminRole = userService.checkAdminRole(user);
        if(checkAdminRole) {
            //管理员
            categoryService.add(addCategoryReq);
            return ApiRestResponse.success();
        }else {
            return ApiRestResponse.error(ImoocMallExceptionEnum.NEED_ADMIN);
        }
    }

  然后在对应的实体中,根据需求添加需要的注解(具体需要哪些注解参考第二条)

public class AddCategoryReq {

    @Size(min=2,max=5)
    @NotNull(message="名称不能为空")
    private String name;

    @Max(3)
    @NotNull(message="类型不能为空")
    private Integer type;

    @NotNull(message="parentId不能为空")
    private Integer parentId;
    
    @NotNull(message="orderNum不能为空")
    private Integer orderNum;
       
    //省略了get set方法
}

4,处理异常,优雅的提示给用户

@ControllerAdvice
public class GlobalExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiRestResponse handleMethodArgumentNotValidException(
            MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException: ", e);
        return handleBindingResult(e.getBindingResult());
    }
    private ApiRestResponse handleBindingResult(BindingResult result) {
        //把异常处理为对外暴露的提示
        List<String> list = new ArrayList<>();
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError objectError : allErrors) {
                String message = objectError.getDefaultMessage();
                list.add(message);
            }
        }
        if (list.size() == 0) {
            return ApiRestResponse.error(ImoocMallExceptionEnum.REQUEST_PARAM_ERROR);
        }
        return ApiRestResponse
                .error(ImoocMallExceptionEnum.REQUEST_PARAM_ERROR.getCode(), list.toString());
    }
}

枚举类信息: 

public class ImoocMallException extends RuntimeException{

    private final Integer code;
    private final String message;
    /**
     * @param code
     * @param message
     */
    public ImoocMallException(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
    
    public ImoocMallException(ImoocMallExceptionEnum enumInfo) {
        this(enumInfo.getCode(),enumInfo.getMsg());
    }

    /**
     * @return the code
     */
    public Integer getCode() {
        return code;
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }
}

public enum ImoocMallExceptionEnum {
    NEED_USER_NAME(10001,"用户名不能为空!"),
    NEED_PASSWORD(10002,"密码不能为空!"),
    PASSWORD_TO_SHORT(10003,"密码不能少于8位!"),
    NAME_EXISTED(10004,"不允许重名!"),
    INSTER_FAILED(10005,"数据插入失败!"),
    WRONG_PASSWORD(10006,"密码错误!"),
    NEED_LOGIN(10007,"用户未登录!"),
    UPDATE_FAILED(10008,"更新失败!"),
    NEED_ADMIN(10009,"无管理员权限!"),
    PARA_NOT_NULL(10010,"参数不能为空!"),
    CREATE_FAILED(10011,"新增失败!"),
    REQUEST_PARAM_ERROR(10012, "参数错误"),
    
    SYSTEM_ERROR(20000,"系统异常!")
    ;
    //异常状态码
    Integer code;
    
    //异常信息
    String msg;

    
    
    /**
     * @param code
     * @param msg
     */
    private ImoocMallExceptionEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    /**
     * @return the code
     */
    public Integer getCode() {
        return code;
    }

    /**
     * @param code the code to set
     */
    public void setCode(Integer code) {
        this.code = code;
    }

    /**
     * @return the msg
     */
    public String getMsg() {
        return msg;
    }

    /**
     * @param msg the msg to set
     */
    public void setMsg(String msg) {
        this.msg = msg;
    }
    
    
}

5,使用postman测试接口

原文地址:https://www.cnblogs.com/ljc1212/p/14071081.html