Controller 층 은 들 어 오 는 매개 변 수 를 검사 하고 매개 변수 검사 주 해 를 사용자 정의 합 니 다 (제어 층 코드 최적화)

controller 층 에서 데 이 터 를 검사 할 때 먼저 @ Valid 주 해 를 사용 하고 자신 이 정의 한 매개 변수 와 대응 하 는 클래스 로 가서 해당 하 는 매개 변수 가 요구 하 는 검 사 를 하고 controller 에서 받 아들 입 니 다.
 @PostMapping(value = "/login_submit")
    public ResponseResult<Boolean> login_submit(@Valid LoginVo loginVo) {
        userService.checkLogin(loginVo);
        return ResponseResult.success(true);
    }

전 송 된 매개 변수 대응 클래스 의 LoginVo 에 들 어가 검 사 를 하려 면 매개 변수 검사 의존 이 필요 합 니 다.
<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;
}


vaidator 에 서 는 빈 메 일, 메 일 같은 주해 검증 을 제공 하지 않 습 니 다. 여기 서 @ IsPhone 을 넣 는 것 은 자신 이 정의 하 는 검사 핸드폰 번호 의 주 해 를 제공 합 니 다. 먼저 이 인터페이스 에 대응 하 는 클래스 를 작성 한 다음 구체 적 인 기능 을 실현 하 는 검사 기 류 를 작성 해 야 합 니 다. 여기 서 구체 적 인 검사 규칙 은 검사 기 규칙 류 를 따로 추출 할 수 있 습 니 다.1. 사용자 정의 인터페이스
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. 구체 적 인 검사 기 구현 클래스
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. 규칙 util 클래스 검사
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();
    }
}

좋은 웹페이지 즐겨찾기