目录
使用场景
1.对于controller入参字段检查
1)自定义注解
2)controller层检查UserDTO中包含List对象
3)检查UserDTO中 private List<String> strList,对其中字符串进行检查直接在List泛型上加检查注解
4)检查List<StudentDTO> 对象
5)对@RequestParam 字段检查
2.springmvc全局异常统一处理
1.对于controller入参字段检查
1)自定义注解
package cn.summit.validation.annotation;
import cn.summit.validation.validor.TextLengthValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.constraints.Min;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 字符串长度检查
*
* @author summit
* @since 2020/6/24 11:19
*/
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Repeatable(TextLength.List.class)
@Constraint(validatedBy = TextLengthValidator.class)
@Documented
public @interface TextLength {
int min() default 0;
int max() default Integer.MAX_VALUE;
String message() default "{javax.validation.constraints.Length.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* Defines several {@link Min} annotations on the same element.
*
* @see Min
*/
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Documented
@interface List {
TextLength[] value();
}
}
package cn.summit.validation.validor;
import cn.summit.validation.annotation.TextLength;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 字符串长度检查
*
* @author summit
* @since 2020/6/24 11:19
*/
public class TextLengthValidator implements ConstraintValidator<TextLength, String> {
private int min;
private int max;
@Override
public void initialize(TextLength annotation) {
this.min = annotation.min();
this.max = annotation.max();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
int length = value.length();
return length >= min && length <= max;
}
}
2)controller层检查UserDTO中包含List对象
在其字段上加上@Valid,才会对List对象进行检查
public class UserDTO implements Serializable {
....
@Valid
private List<StudentDTO> studentList;
3)检查UserDTO中 private List<String> strList,对其中字符串进行检查
直接在List泛型上加检查注解
private List< @TextLength(max = 3) String> strList;
4)检查List<StudentDTO> 对象
1.在controller上加上注解
2. public Result<String> test(@RequestBody @Valid List<UserDTO> list) {
5) 对@RequestParam 字段检查
1.需要在controller上加上 @Validated
public void getTestVal(@PathVariable @TextLength(max = 5) String val) {
2.springmvc全局异常统一处理
@RestControllerAdvice
@Slf4j
public class GlobalBaseController implements ResponseBodyAdvice<Object> {
/**
* 用于处理通用异常
*/
@ExceptionHandler(Throwable.class)
public Result<?> errorHandler(Throwable e, HttpServletResponse response) {
// log.info("headers {}", headers);
log.error("", e);
return Result.failed("后台异常,请联系管理员");
}
/**
* 用于处理通用异常 捕获 未加@RequestBody
*/
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result<?> bindException(BindException e) {
BindingResult bindingResult = e.getBindingResult();
StringBuilder errorMesssage = new StringBuilder("校验失败:");
for (FieldError fieldError : bindingResult.getFieldErrors()) {
errorMesssage.append(fieldError.getField()).append(":")
.append(fieldError.getDefaultMessage()).append(fieldError.getRejectedValue())
.append("; ");
}
log.error(errorMesssage.toString());
return Result.failed(errorMesssage.toString());
}
/**
* 用于处理通用异常 捕获 @Validated UserDTO list
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result<?> bindException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
StringBuilder errorMesssage = new StringBuilder("校验失败:");
for (FieldError fieldError : bindingResult.getFieldErrors()) {
errorMesssage.append(fieldError.getField()).append(":")
.append(fieldError.getDefaultMessage()).append(fieldError.getRejectedValue())
.append("; ");
}
log.error(errorMesssage.toString());
return Result.failed(errorMesssage.toString());
}
/**
* 用于处理通用异常
*
* 捕获 @RequestBody @Valid List<UserDTO> list 和 getTestVal(@PathVariable @TextLength(max = 5)
* String val)
*/
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result<?> bindException(ConstraintViolationException e) {
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
StringBuilder errorMesssage = new StringBuilder("校验失败:");
for (ConstraintViolation<?> constraintViolation : constraintViolations) {
errorMesssage.append(constraintViolation.getMessage());
log.error(constraintViolation.getMessage());
}
return Result.failed(errorMesssage.toString());
}
网友评论