개발을 하면 Request로 들어오는 값이 null 값인지 아닌지 빈 문자열인지 확인이 필요하다. Service 단(비즈니스 로직)에서 값을 확인을 해도 된다. 하지만 기능이 실행되기 전에 확인을 해야 한다. 값이 없거나 잘못된 경우 오류가 나기 때문에 Controller 에서 값을 확인하는 게 더 간결한 코드를 작성하고 처리를 하는 게 유리하다.
값을 확인할 때 스프링부트에서는 validation 플러그인을 이용하면 쉽게 유효성을 확인할 수 있다.
implementation 'org.springframework.boot:spring-boot-starter-validation'
플러그인을 추가 후 Request 로 값을 받는 DTO 파일을 연다.
package com.study.valid_test.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.*;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
public class UserDto {
@NotBlank(message = "이름을 확인해주세요.")
@JsonProperty("name")
private String name;
@Min(value = 0, message = "나이를 확인해주세요.")
@JsonProperty("age")
private int age;
@Email
@NotBlank(message = "이메일을 확인해주세요.")
@JsonProperty("email")
private String email;
@Builder
public UserDto(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
}
위에서 사용한 어노테이션 중 @NotBlank, @Min 이 Validation 의 기능이다. 들어오는 파라미터의 값에 선언을 해주면 된다.
Validation 어노테이션 종류
어노테이션 이름 | 기능 |
@AssertFalse | False일 경우 |
@AssertTrue | True일 경우 |
@DecimalMax(value=) | 지정 값 이하 실수 |
@DecimalMin(value=) | 지정 값 이상 실수 |
@Digits(integer=,fraction=) | 속성 값이 지정된 정수화 소수 자리수보다 적을 경우 |
@Future | 속성 날짜가 현재보다 미래인 경우 |
@Past | 속성 날짜가 현재보다 과거인 경우 |
@Max(value) | 지정 값이하인 경우 |
@Min(value) | 지정 값이상인 경우 |
@NotNull | 널이 아닌 경우 |
@Null | 널인 경우 |
@Pattern(regex=, flag=) | 해당 정규식 통과인 경우 |
@Size(min=, max=) | 문자열 또는 배열이 지정값 사이인 경우 |
@Valid | 확인 조건 만족한 경우 |
package com.study.valid_test.api.controller;
import com.study.valid_test.common.url.Url;
import com.study.valid_test.dto.UserDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Tag(name = "Valid", description = "DTO Valid API")
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(Url.api + Url.v1)
public class ValidController {
@Operation(summary = "Valid Check API", description = "Valid 체크 테스트")
@GetMapping(Url.valid)
public ResponseEntity<?> testValid(@Valid UserDto userDto) {
return ResponseEntity.ok("Valid check Success");
}
}
들어오는 파라미터에 Validation 의 어노테이션을 선언 후 Controller 로 에서 들어오는 파라미터에 @Valid 를 붙여준다. 그러면 모든 요청을 처리하는 디스패처 서블릿으로 전달되는 과정에서 ArgumentResolver 에 의해 처리된다.
@Valid 는 기본적으로 컨트롤러에서만 동작하며 다른 계층에서는 검증이 되지 않는다. 다른 계층에서 검증하기 위해서는 @Validated 와 결합하여 사용해야 한다.
스프링부트 Validation 간단 예제
https://github.com/ihseo01/valid_example
GitHub - ihseo01/valid_example: Simple Valid Example
Simple Valid Example. Contribute to ihseo01/valid_example development by creating an account on GitHub.
github.com
'Framework > Springboot' 카테고리의 다른 글
스프링부트로 네이버 로그인 구현하기 - 설정 (2) | 2024.01.26 |
---|---|
WebClient 이해하기 (2) | 2024.01.25 |
RestTemplate 이해하기 (0) | 2024.01.24 |
스프링부트로 카카오 로그인 구현하기 - 설정 (0) | 2024.01.23 |