3.2 JSR 引數校驗與攔截
阿新 • • 發佈:2021-07-10
1 引入JSR依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
2 校驗
- 1 新增 @Valid 標籤
public Result<Boolean> doLogin(LoginVo loginVo){ --> public Result<Boolean> doLogin(@Valid LoginVo loginVo){
- 2 在校驗的實體類中新增@NotNull 標籤
@NotNull@IsMobile
private String mobile;@NotNull@Length(min=32)
private String password;
- 3 編寫介面 並制定校驗器
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE}) @Retention(RetentionPolicy.RUNTIME) @Documented@Constraint(validatedBy = {IsMobileValidator.class}) public @interface IsMobile { boolean require() default true; String message() default "手機號碼格式錯誤"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {};}
- 4 重新編寫校驗器
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> { private boolean required = false; @Override public void initialize(IsMobile constraintAnnotation) { required = constraintAnnotation.require(); } @Override public boolean isValid(String value, ConstraintValidatorContext context) { if(required){ return ValidatorUtil.isMobile(value); }else{ if(StringUtils.isEmpty(value)){ return true; }else{ return ValidatorUtil.isMobile(value); } } } }
3 攔截
- 建立exception 包和GlobelExceptionHandler 類
@ControllerAdvice@ResponseBodypublic class GlobleExceptionHandler {
@ExceptionHandler(value=Exception.class)
public Result<String> exceptionHandler(HttpServletRequest request, Exception e){
if(e instanceof BindException){
BindException ex = (BindException) e; List<ObjectError> errors = ex.getAllErrors(); ObjectError error = errors.get(0); String msg = error.getDefaultMessage(); return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg)); }else{
return Result.error(CodeMsg.SERVER_ERROR); }
}
}
4 編寫全域性異常
public class GlobleException extends RuntimeException{
private static final long serialVersionUID = 7103829434715939102L; public CodeMsg getCm() {
return cm; }
private CodeMsg cm; public GlobleException(CodeMsg cm){
super(cm.toString()); this.cm = cm; }
}
5 在sevice層遇到異常,直接丟擲異常
public CodeMsg login(LoginVo loginVo) {
if(loginVo == null){
// return CodeMsg.SERVER_ERROR; throw new GlobleException(CodeMsg.SERVER_ERROR); }