七爪源码:Spring Boot 应用程序使用 @valid 验证 API 请求

使用 @valid 可以使您的请求验证更容易。

七爪源码:Spring Boot 应用程序使用 @valid 验证 API 请求

我们在开发rest API的时候,相信大家都需要验证接口输入参数的合法性。 一些初学者可能会使用很多 if-else 条件表达式进行验证。 以新用户注册为例:

@RestController
public class DemoController {


    @PostMapping("/user/register")
    public Boolean registerUser(@RequestBody UserRegisterRequest request) {

        if (StringUtils.isBlank(request.getName() == null)) {
            throw new IllegalArgumentException("username is required");
        }

        if (StringUtils.isBlank(request.getpassword())) {
            throw new IllegalArgumentException("password is required");
        }

        if (StringUtils.isBlank(request.getEmail())) {
            throw new IllegalArgumentException("email is required");
        }
        
		..........
    }
}

这样的代码可以达到参数验证的目的,但是细心的读者可能已经发现,如果我们要写很多这样的接口,就需要重复写很多验证码,显然不优雅。 我们可以使用@valid 注解来帮助我们简化验证逻辑。


使用@Valid

hibernate-validator 实现了@Valid。 spring-boot-start-web 已经包含了这个库,所以不需要引入依赖。 如果是非spring项目,需要用到两个Maven依赖。


    javax.validation
    validation-api
    2.0.1.Final

 

    org.hibernate
    hibernate-validator
    6.0.14.Final

以下是@valid 相关的注解。对实体类的属性添加不同的注解可以实现校验功能。

  • @Null 限制属性只能为空。
  • @NotNull 限制属性不可为空。
  • @Max(value) 限制属性必须是不大于指定值的数字。
  • @Min(value) 限制属性必须是不小于指定值的数字。
  • @Digits(integer, fraction) 限制属性必须是小数,整数部分的位数不能超过整数,小数部分的位数不能超过分数。
  • @Past 限制属性必须是过去的日期。
  • @Future 限制属性必须是未来日期。
  • @Pattern(value) 限制属性必须符合指定的正则表达式。
  • @Size(max, min) 限制字符长度必须在 min 和 Max 之间。
  • @NotEmpty 有效属性值不可为空,字符串长度不为0,集合大小不为0。
  • @NotBlank 有效属性值不为空,并且在 trim() 之后长度不为 0。
  • @Email 验证属性值是电子邮件格式的字符串。

使用@valid注解完成参数校验非常简单。您只需要在实体类的属性上添加适当的注解即可。上面是新用户注册的相同示例。

public class UserRegisterRequest {

    @Pattern(regexp = "1[3-9]{1}[0-9]{9}", message = "the user phone is illegal.")
    private String phone;
    @Email
    private String email;
    @NotBlank(message = "username is required.")
    @Size(min = 1, max = 225, message = "username is too long.")
    private String username;
    @NotBlank(message = "password is required.")
    @Min(value = 8, message = "The new password is too short.")
    private String password;

    //If entity nesting exists, @valid annotation must be added
    @Valid
    @NotNull
    private Address address;
    
    .....
}

public class Address {

    @NotBlank
    private String provice;

    @NotBlank
    private String city;

    @NotBlank
    private String detailAddress;
}

@RestController
public class DemoController {


    @PostMapping("/user/register")
    public Boolean registerUser(@Valid @RequestBody UserRegisterRequest request) {

    }

看,就这么简单。 一些注释完成了复杂的验证逻辑。 当目标参数校验失败时,系统会抛出 MethodArgumentNotValidException 异常。 然后,我们可以使用@ExceptionHandler 处理验证结果。


使用@Exceptionhandler 统一处理验证结果

public class ErrorResult implements Serializable {

    private long code;
    private String msg;

    public long getCode() {
        return code;
    }

    public void setCode(long code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

@Component 
public class GlobalExceptionHandler {  
  
    
    @ResponseStatus(HttpStatus.BAD_REQUEST)  
    @ExceptionHandler(MethodArgumentNotValidException.class)  
    public ErrorResult parameterExceptionHandler(MethodArgumentNotValidException e) {  
    BindingResult exceptions = e.getBindingResult();  
     if (exceptions.hasErrors()) {  
            List errors = exceptions.getAllErrors();  
            if (!errors.isEmpty()) {  
                
                FieldError fieldError = (FieldError) errors.get(0); 
                return new ErrorResult(-1,fieldError.getDefaultMessage()); 
                }
          }
          
        return new ErrorResult(-1,"argument valid failure");    
    }  

此处创建了一个全局异常处理程序类。 我们使用 parameterExceptionHandler 方法来捕获 MethodArgumentNotValidException 异常,最终统一处理验证失败的结果。 该方法会在每个字段的验证失败后得到错误信息。 在这里,我使用 ErrorResult 类来返回错误消息。 当我们启动服务时,我们使用 postman 发起一个 post 请求,我们不输入任何参数并返回结果:

{  
    "code": -1,  
    "msg": "the user phone is illegal."  
}

本文简单介绍了spring boot中使用@valid验证API请求。 我希望这篇文章可以帮助你。 感谢您的阅读。

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章