SpringBoot使用JSR303做参数校验

1. 实体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class User {
@NotNull
private Integer id;

@NotNull
private String name;

@NotNull
@Length(min=6)
private String password;

@NotNull
@IsPhone //自定义的校验
private String phone;
}

#2. Controller中使用

1
2
3
4
@PostMapping(value="login")
public String login(@Valid User user) {

}

3. 自定义校验

注解IsPhone 判断是否为手机号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.pibigstar.springboot.validator;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {PhoneValidator.class})
public @interface IsPhone {

boolean required() default true;

String message() default "手机号不合法"; //错误默认提示信息

Class<?>[] groups() default { };

Class<? extends Payload>[] payload() default { };

}

4. 实现具体校验类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.pibigstar.springboot.validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
* 手机号码验证者
* @author pibigstar
*
*/
public class PhoneValidator implements ConstraintValidator<IsPhone,String>{

private boolean requeired;
@Override
public void initialize(IsPhone constraintAnnotation) {
requeired = constraintAnnotation.required();
}


@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (requeired) {
return isPhone(value);
}else {
//phone 不是必须
if (value==null||value.length()==0) {
return true;
}else {
return isPhone(value);
}
}
}

private boolean isPhone(String phone) {
//以1开头,后面跟10个整数,一共11位
Pattern phonePattern = Pattern.compile("1\\d{10}");
if (phone==null||phone.length()<=0) {
return false;
}else {
Matcher matcher = phonePattern.matcher(phone);
return matcher.matches();
}
}
}

5. 对参数不通过进行统一捕获

参数验证不通过后统一格式返回给前端页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.pibigstar.springboot.exception;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pibigstar.springboot.domain.result.MyResponse;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

@ExceptionHandler(value=Exception.class)
public MyResponse exceptionHandler(HttpServletRequest request,Exception e) {
//参数校验异常
if (e instanceof BindException) {
BindException exception = (BindException) e;
List<ObjectError> allErrors = exception.getAllErrors();
ObjectError objectError = allErrors.get(0);
String defaultMessage = objectError.getDefaultMessage();
return MyResponse.error(defaultMessage);
}else {
//其他异常
return MyResponse.error(e);
}
}
}
-------------本文结束感谢您的阅读-------------