springboot使用Validator 进行参数验证

1:在pom.xml添加依赖



	org.springframework.boot
	spring-boot-starter-parent
	2.1.9.RELEASE
	 


    
       org.springframework.boot
       spring-boot-starter-web
     
     
     
       javax.validation
       validation-api
     

2: 在Dto类里面添加验证规则,验证规则根据不同需求添加

@Data
public class UserUpdatePasswordDto implements Serializable {


    private String userId;

    @NotNull(message = "旧密码不能为空")
    private String oldPassword;

    @NotNull(message = "新密码不能为空")
    private String newPassword;

    private String againPassword;

}

3:在Controller中配置入参,在方法前添加@Validated注解,使验证规则生效

    @RequestMapping("/update")
    public String updateUserPassword(@Validated UserUpdatePasswordDto dto){
        return "success";
    }

4:使用postman测试结果

springboot使用Validator 进行参数验证_第1张图片

5:为了统一异常处理,采用全局异常处理

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 实体类验证异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public String handleBindException(BindException e){

        List errors = e.getAllErrors();
        for (ObjectError error : errors){
            System.out.println(error.getDefaultMessage());
        }
        return JSON.toJSONString(ReponseResult.error(e.getBindingResult().getFieldError().getDefaultMessage()));
    }

    /**
     * 单个参数异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public String handleConstraintViolationException(ConstraintViolationException e){
        List errorList = new ArrayList<>();
       Set> errorSet =  e.getConstraintViolations();
       for (ConstraintViolation c : errorSet){
           errorList.add(c.getMessage());
       }
        return JSON.toJSONString(ReponseResult.error(String.join(",",errorList)));
    }

}
@Data
public class ReponseResult implements Serializable {

    private Integer code;

    private Boolean success;

    private String message;

    private Object data ;

    public ReponseResult(Boolean success, String message) {
        this.success = success;
        this.message = message;
    }

    public static ReponseResult error(String message) {
        ReponseResult reponseResult = new ReponseResult(false,message);
        return reponseResult;
    }
}

再次请求结果

springboot使用Validator 进行参数验证_第2张图片

6:单个参数请求

  类上添加注解@Validated ,方法上添加验证规则

@RestController
@RequestMapping("/web")
@Validated
public class WebController {
    
    @RequestMapping("/getPhone")
    public String getUserPhone(@NotNull(message = "员工工号不能为空") String userId) {
        return "success";
    }
}

 

你可能感兴趣的:(spring,boot)