Controller 층 은 들 어 오 는 매개 변 수 를 검사 하고 매개 변수 검사 주 해 를 사용자 정의 합 니 다 (제어 층 코드 최적화)
15772 단어 웹 주류 프레임 워 크spring정규 표현 식
@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();
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Spring Tool Suite (STS) 설치, 일본어 및 Gradle 플러그인 추가 단계Spring 애플리케이션 개발을 위한 통합 개발 환경으로 Spring Tool Suite(STS)를 설치하는 절차를 설명합니다. 필요에 따라 일본어화와 Gradle 플러그인을 추가하는 절차도 이용하십시오. 설치 대상...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.