spring-boot-starter-validation 校验参数的实现

目录

t; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import lombok.extern.slf4j.Slf4j; @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = BindException.class) public jsonResult exceptionHandle(BindException exception) { BindingResult result = exception.getBindingResult(); StringBuilder errorMsg = new StringBuilder(); List<FieldError> fieldErrors = result.getFieldErrors(); fieldErrors.forEach(error -> { log.error("field: " + error.getField() + ", msg:" + error.getDefaultMessage()); errorMsg.append(error.getDefaultMessage()).append("!"); }); return JsonResult.fail(errorMsg.toString()); } @ExceptionHandler(value = MethodArgumentNotValidException.class) public JsonResult MyExceptionHandle(MethodArgumentNotValidException exception) { BindingResult result = exception.getBindingResult(); StringBuilder errorMsg = new StringBuilder(); List<FieldError> fieldErrors = result.getFieldErrors(); fieldErrors.forEach(error -> { log.error("field: " + error.getField() + ", msg:" + error.getDefaultMessage()); errorMsg.append(error.getDefaultMessage()).append("!"); }); return JsonResult.fail(errorMsg.toString()); } // 处理运行时异常 @ExceptionHandler(RuntimeException.class) public JsonResult doHandleRuntimeException(RuntimeException e) { log.error(e.getMessage(), e); e.printStackTrace(); return JsonResult.fail(e.getMessage()); } }

另外JsonResult.java用于接口返回统一个json格式

import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; /** *@author wang *@Date 2020-9-14 * **/ @Data @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class JsonResult<T> { /** 成功 */ public static final int SUCCESS=200; /**内部服务器错误**/ public static final int FAIL=500; /** 没有登录 */ public static final int NOT_LOGIN = 400; /** 发生异常 */ public static final int EXCEPTION = 401; /** 系统错误 */ public static final int SYS_ERROR = 402; /** 参数错误 */ public static final int PARAMS_ERROR = 403; /** 不支持或已经废弃 */ public static final int NOT_SUPPORTED = 410; /** AuthCode错误 */ public static final int INVALID_AUTHCODE = 444; /** 太频繁的调用 */ public static final int TOO_FREQUENT = 445; /** 未知的错误 */ public static final int UNKNOWN_ERROR = 499; private Integer code; private String msg; private T data; public static JsonResult fail() { return new JsonResult(FAIL, "请求处理失败",null); } public static JsonResult fail(String msg) { return new JsonResult(FAIL, msg,null); } public static JsonResult fail(Integer code,String msg) { return new JsonResult(code, msg,null); } public static JsonResult success() { return new JsonResult(SUCCESS,"请求处理成功",null); } public static JsonResult success(String msg) { return new JsonResult(SUCCESS,msg,null); } public static <T> JsonResult success(T data) { return new JsonResult<T> (SUCCESS,"请求处理成功",data); } public static <T> JsonResult success(String msg,T data) { return new JsonResult<T>(SUCCESS, msg,data); } public static JsonResult err() { return build(EXCEPTION); } public static JsonResult err(String msg) { return build(EXCEPTION, msg); } public JsonResult<T> code(int code) { this.code = code; return this; } public JsonResult<T> msg(String msg) { this.msg = msg; return this; } public JsonResult<T> data(T data) { this.data = data; return this; } public static JsonResult build() { return new JsonResult(); } public static JsonResult build(int code) { return new Jsonhttp://www.cppcns.comResult().code(code); } public static JsonResult build(int code, String msg) { return new JsonResult<String>().code(code).msg(msg); } public static <T> JsonResult<T> build(int code, T data) { return new JsonResult<T>().code(code).data(data); } public static <T> JsonResult<T> build(int code, String msg, T data) { return new JsonResult<T>().code(code).msg(msg).data(data); } }

当然还有其他异常处理方式可以参考:https://www.jb51.net/article/244379.htm

七、测试效果

八、嵌套对象的校验

import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.*; @Data public class User { @NotEmpty(message = "用户名不能为空") @Size(message = "长度 [1-3] ", min = 1, max = 3, groups = ValidateGroup.FirstGroup.class) private String username; @Min(message = "id不得小于0", value = 0) private Integer id; @NotBlank(message = "地址不能为空", groups = {ValidateGroup.ThirdGroup.class, ValidateGroup.SecondeGroup.class}) private String address; //在内部属性是自定义对象的时候添加 @Valid 注解 ,即可开启对In对象的校验。 //记得添加@NotNull注解,否则该对象可以为null,并且此时In对象的校验规则也不会抛出异常 。 @Valid @NotNull(message = "In 对象不能为null ", groups = {ValidateGroup.ThirdGroup.class, ValidateGroup.SecondeGroup.class}) private In in; }

/** *自定义的对象,User对象中的一个属性。 */ @Data public class In { @NotBlank(message = "str不能为空", groups = {ValidateGroup.ThirdGroup.class, ValidateGroup.SecondeGroup.class}) private String str; }

九、自定义注解(自定义校验规则)

9.1 实现ConstraintValidator接口

import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class WordConstraintValidator implements ConstraintValidator<CustomValidaor, Object> { @Override public boolean isValid(Object value, ConstraintValidatorContext context) { // 具体的校验规则 return value.toString().length() == 10; } }

9.2 自定义注解

import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Target({ ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = WordConstraintValidator.class) public @interface CustomValidaor { String message(); // groups 和 payload 这两个parameter 必须包含,不然会报错 Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }

9.3 使用

@Data public class Inner { @NotBlank(message = "str不能为空", groups = { ValidateGroup.ThirdGroup.class, ValidateGroup.SecondeGroup.class }) @CustomValidaor(message = "长度必须为10", groups = { ValidateGroup.ThirdGroup.class, ValidateGroup.SecondeGroup.class }) private String str; }

9.4测试

访问接口

@PostMapping("test6") public User test6(@Validated({ValidateGroup.SecondeGroup.class}) @RequestBody User u) { System.out.println(u); return u; }

到此这篇关于spring-boot-starter-validation 校验参数的实现的文章就介绍到这了,更多相关spring-boot-starter-validation 校验参数内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

发布于 2022-04-22 18:01:12
收藏
分享
海报
0 条评论
24
上一篇:hibernate-validator如何使用校验框架 下一篇:Java中synchronized用法汇总
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码