1) Validation
Validation이란 올바르지 않은 데이터를 걸러내고 보안을 유지하기 위해 데이터 검증(Validation)은 여러 계층에 걸쳐서 적용됩니다.
Client의 데이터는 조작이 쉬울 뿐더러 모든 데이터가 정상적인 방식으로 들어오는 것이 아니기 때문에, Client Side뿐만 아니라 Server Side에서도 데이터 유효성을 검사해야 할 필요가 있습니다.
스프링부트 프로젝트에서는 @Validated를 이용해 유효성을 검증할 수 있습니다.
2) 사용 방법
memberController.java
public MemberVO getMemberDetail(@Validated MemberQuery memberQuery) {
code
}
Contoller에서 유효성 검사를 적용할 API의 Request 객체 앞에 @Validated 어노테이션을 추가합니다.
MemberVO.java
@Getter
@Builder
@NoArgsConstructor
public class MemberVO {
@NotBlank(message="NAME_IS_MANDATORY")
private String name;
@NotBlank(message="PASSWORD_IS_MANDATORY")
private String password;
@Email(message = "NOT_VALID_EMAIL")
private String email;
}
Request를 핸들링 할 객체를 정의할 때 Validation 어노테이션을 통해 필드별로 필요한 유효성 검사를 적용합니다.
유효성 검사에 적용할 수 있는 어노테이션은 다음과 같습니다.
@Null // null만 허용합니다.
@NotNull // null을 허용하지 않습니다. "", " "는 허용합니다.
@NotEmpty // null, ""을 허용하지 않습니다. " "는 허용합니다.
@NotBlank // null, "", " " 모두 허용하지 않습니다.
@Email // 이메일 형식을 검사합니다. 다만 ""의 경우를 통과 시킵니다
@Pattern(regexp = ) // 정규식을 검사할 때 사용됩니다.
@Size(min=, max=) // 길이를 제한할 때 사용됩니다.
@Max(value = ) // value 이하의 값을 받을 때 사용됩니다.
@Min(value = ) // value 이상의 값을 받을 때 사용됩니다.
@Positive // 값을 양수로 제한합니다.
@PositiveOrZero // 값을 양수와 0만 가능하도록 제한합니다.
@Negative // 값을 음수로 제한합니다.
@NegativeOrZero // 값을 음수와 0만 가능하도록 제한합니다.
@Future // 현재보다 미래
@Past // 현재보다 과거
@AssertFalse // false 여부, null은 체크하지 않습니다.
@AssertTrue // true 여부, null은 체크하지 않습니다.
해당 기능들에 대한 더 세부적인 내용은 이 사이트를 참고.
RR.
'백엔드 > Spring' 카테고리의 다른 글
[Spring] Cookie와 Session 그리고 JWT 토큰 (3) | 2024.03.08 |
---|---|
[Swagger] 스웨거(Swagger) Annotation, Validation (0) | 2024.02.28 |
[Spring Security] CSRF 토큰 (0) | 2024.02.26 |
[Spring] Spring IoC 컨테이너, Bean (0) | 2024.01.16 |
[Spring] 필터(Filter)와 인터셉터(Interceptor) (1) | 2024.01.10 |