SpringBoot learning seckill II. jsr303 calibrator

Form verification is an indispensable link when we submit a form. The common verification method is to judge each parameter separately, but this is not only troublesome, but also if we write too many if parameters, the code will be bloated and the readability will be poor. Take login as an example, suppose we need mobile and password For two parameters, you need to check as follows:

if(StringUtils.isEmpty(mobile)){
	return false;
}
if(!Validator.isMobile(mobile)){
	return false;
}
if(StringUtils.isEmpty(password)){
	return false;
}

At this time, our jsr303 will shine
For the same example, we define a UserVO to receive the parameters of the front end

public class UserVo {
    private String mobile;
    private String password;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Then we define our controller, UserController:

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("login")
    public String login(UserVo userVo){
        return "";
    }

}

Next, add the dependency of jsr303 in pom.xml:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

In this way, when the Controller passes the parameter, we use @ Valid to tell the system that this parameter needs to be verified
@Valid UserVo userVo
Next, we just need to go to Vo and use annotations on the variables to be verified. For example, if we need a password that is not empty, we can use @ NotNull. If we need to limit the minimum password length to no less than 8 bits, we can use @ Length(min = 8). In addition, the system also provides us with many annotations:

 @NotNull annotation element must be non empty
 @Null annotation element must be empty
 @Digital verifies whether the digital composition is legal
 @Future verifies whether it is after the current system time
 @Past verifies that it is before the current system time
 @Max verifies that the value is less than or equal to the maximum specified integer value
 @Min verifies whether the value is greater than or equal to the minimum specified integer value
 @Pattern verifies that the string matches the specified regular expression
 @Size verifies that the element size is within the specified range
 @DecimalMax validates that the value is less than or equal to the maximum specified small value
 @DecimalMin verifies that the value is greater than or equal to the minimum specified small value
 @AssertTrue the annotated element must be true
 @AssertFalse the annotated element must be false

If the verification method we need is not available in the system, we can also implement one by ourselves. For example, if we need to verify whether mobile is a correct mobile number, we can define a @ IsMobile by ourselves:

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
        validatedBy = {IsMobileValidator.class}   // Here is the specific implementation of parameter verification
)
public @interface IsMobile {

    boolean required() default true;   //Whether to define by yourself indicates whether the attribute must be filled in

    String message() default "Mobile number format error";  //Prompt after verification failure

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

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

}

Now that the annotation is available, we need to implement a method to verify the mobile phone number, that is, IsMobileValidator in the upper annotation validateby = {IsMobileValidator. Class}, which needs to implement constraintvaliditor < annotation, parameter type > interface:

public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {

    private boolean required = false;

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        //If the parameter must be filled in, check it
        if(required){
            return ValidatorUtil.isMobile(s);
        }
        //If the parameter is not required, then if it is empty, it also meets the requirements
        if(StringUtils.isEmpty(s)){
            return  true;
        }
        return ValidatorUtil.isMobile(s);
    }
}

The specific implementation of the class to determine whether the string is a phone number ValidatorUtil:

/**
 * Parameter verification tool
 * author:shine
 */
public class ValidatorUtil {

    /**
     * Verify cell phone number
     * @param mobile
     * @return
     */
    public static boolean isMobile(String mobile){
        Pattern mobilePattern =  Pattern.compile("^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$");
        Matcher m = mobilePattern.matcher(mobile);
        return m.matches();
    }

}

OK, so the @ IsMobile annotation is implemented. Let's write this annotation on the mobile parameter:

public class UserVo {

    @IsMobile
    private String mobile;
    @NotNull
    @Length(min = 8)
    private String password;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Next, let's test. Since we haven't written the page yet, here we use postman to simulate the request:

When our mobile phone number and password are correct, we can see that there is no error and no report, indicating that our request parameters have passed the verification. Next, let's try to use a password less than 8 in length:

You can see that the requested message is an error message. Next, we use an illegal mobile number to test:

You can see that our custom verification is also OK

Published 10 original articles, won praise 1, visited 3299
Private letter follow

Tags: Mobile less xml Spring

Posted on Sat, 22 Feb 2020 09:33:57 -0500 by plazz2000