Java秒杀系统方案优化,高性能高并发实战

释放双眼,带上耳机,听听看~!

Validator

springboot validation为我们提供了常用的校验注解,比如@notNull,@notBlant等注解,但有时候这些并不能满足我们的需求。
比如当用户登录的时候需要输入手机号和密码,那么如何判断手机号码格式是否正确呢,这时就需要我们自定义Validator来校验手机号码

首先在pom.xml引入spring-boot-starter-validation依赖


1
2
3
4
5
6
1<dependency>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-validation</artifactId>
4</dependency>
5
6

编写ValidatorUtil工具类,使用正则表达式判断试机号码是否为以1开头的11位数字


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1/*判断手机号格式是否正确*/
2public class ValidatorUtil {
3
4    //正则表达式:1\d{10}表示1后面接10位数字
5    private static final Pattern mobile_pattern = Pattern.compile("1\\d{10}");
6
7    public static boolean isMobile(String src) {
8        if (StringUtils.isEmpty(src)) {
9            return false;
10        }
11        Matcher m = mobile_pattern.matcher(src);
12        //如果匹配则返回true
13        return m.matches();
14    }
15}
16
17

自定义@IsMobile来校验前端发送过来的手机号格式是否正确


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1/**
2 * 配置 @IsMobile 注解
3 */
4@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})//指定使用范围
5@Retention(RUNTIME)////该注解被保留的时间长短 RUNTIME:在运行时有效
6@Documented
7@Constraint(validatedBy = {IsMobileValidator.class})//指定校验器
8public @interface IsMobile {
9    //是否是必需字段,默认为true
10    boolean required() default true;
11
12    String message() default "手机号码格式错误";
13    //下面两行是自定义注解需要添加的
14    Class<?>[] groups() default {};
15    Class<? extends Payload>[] payload() default {};
16}
17
18

@Target :表示修饰的范围
@Retention :表示注解被保留的时间长短
@Constraint:指定处理校验规则的类
String message(): 必须有的注解属性字段,该字段是用来定义不符合规则错误信息提示用的
boolean required():自定义的注解熟悉字段,该字段表示被@IsMobile标注的字段是否是必需字段

可以看到我们在@Constraint(validatedBy = {IsMobileValidator.class})指定了校验器,接下来看看校验器的实现:

IsMobileValidator校验器


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
1/**
2 * 参数校验器
3 */
4public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {
5
6    private boolean required = false;
7
8    public void initialize(IsMobile constraintAnnotation) {
9        required = constraintAnnotation.required();
10    }
11    //校验
12    public boolean isValid(String value, ConstraintValidatorContext context) {
13        if (required) {
14            //调用工具类对手机号码进行校验
15            return ValidatorUtil.isMobile(value);
16        } else {
17            if (StringUtils.isEmpty(value)) {
18                return true;
19            } else {
20                return ValidatorUtil.isMobile(value);
21            }
22        }
23    }
24}
25
26

可以看到自定义的校验器需要实现ConstraintValidator接口实现 initialize 和 isValid方法,逻辑很简单这里就不多说了,然后来看看如何使用@IsMobile注解:

在mobile字段上标注@IsMobile注解,在controller对需要校验的参数标注@Valid注解


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
1/**
2 * 实体类
3 */
4public class LoginVo {
5
6    @NotNull
7    //自定义注解
8    @IsMobile
9    private String mobile;
10
11    @NotNull
12    @Length(min = 32)
13    private String password;
14
15/**
16 * 控制器
17 */
18@Controller
19@RequestMapping("/login")
20public class LoginController {
21
22    @RequestMapping("/do_login")
23    @ResponseBody
24    public Result<Boolean> doLogin(@Valid LoginVo loginVo) {//在需要校验的参数前添加@Valid注解
25        //登录
26        userService.login(loginVo);
27        return Result.success(true);
28    }
29}
30
31

Validator校验失败会抛出BindExeption异常,捕获后返回给前端错误信息

[图片上传失败…(image-add3e4-1569393652603)]

给TA打赏
共{{data.count}}人
人已打赏
安全技术

使用bootstrap的栅栏实现五列布局

2021-12-21 16:36:11

安全技术

从零搭建自己的SpringBoot后台框架(二十三)

2022-1-12 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索