SpringBoot optimizes the control layer code, uses @Valid to verify the incoming parameters, and customizes a parameter verification annotation

At the controller layer, first use the @Valid annotation to verify the data, go to the class defined by yourself and the corresponding input parameter, check the corresponding parameter requirements, and
accept it in the controller.

 @PostMapping(value = "/login_submit")
    public ResponseResult<Boolean> login_submit(@Valid LoginVo loginVo) {
    
    
        userService.checkLogin(loginVo);
        return ResponseResult.success(true);
    }

Enter the LoginVo of the corresponding class of the incoming parameter for verification.
Parameter verification dependency is required

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
import com.example.validator.IsPhone;
import lombok.Data;
import javax.validation.constraints.NotEmpty;

@Data
public class LoginVo {
    
    

    @NotEmpty(message = "手机号不能为空!")//该注解只能验证String
    @IsPhone//check phone
    private String phone;

    @NotEmpty(message = "密码不能为空!")
    private String password;
}

The validator provides some annotation verifications such as the verification cannot be empty, mailboxes and the like.
Here, @IsPhone is a self-defined annotation verification of the mobile phone number.
First, you must write the class corresponding to this interface, and then write the implementation of specific functions. Validator class, the specific validation rules here can be a separate validator rule class.
1. Custom interface

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

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

    boolean required() default false;
    String message() default "手机号格式错误,请重新输入!";
    Class<?>[] groups() default {
    
    };
    Class<? extends Payload>[] payload() default {
    
    };

}

2. Specific validator implementation class

import com.example.util.ValidatorUtil;
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class IsPhoneValidator implements ConstraintValidator<IsPhone,String> {
    
    

    private boolean required = false;
    public void initialize(IsPhone constraintAnnotation) {
    
    
        required = constraintAnnotation.required();
    }

    public boolean isValid(String value, ConstraintValidatorContext var2){
    
    
        if(required){
    
    
            return ValidatorUtil.isPhone(value);
        }else {
    
    
            if(StringUtils.isEmpty(value)){
    
    
                return true;
            }else {
    
    
                return ValidatorUtil.isPhone(value);
            }
        }
    }

}

3. Validation rules util class

import org.apache.commons.lang3.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidatorUtil {
    
    
    private static final Pattern phone_patten = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
    public static boolean isPhone(String str){
    
    
        if(StringUtils.isEmpty(str)){
    
    
            return false;
        }
        Matcher m = phone_patten.matcher(str);
        return m.matches();
    }
}

Guess you like

Origin blog.csdn.net/Wangdiankun/article/details/106176103