πŸ’ Spring

Spring Validation을 톡해 데이터 μœ νš¨μ„± κ²€μ¦ν•˜κΈ°

iseunghan 2023. 6. 30. 16:15
λ°˜μ‘ν˜•

Validation

μš”μ²­ λ°μ΄ν„°μ˜ μœ νš¨μ„± 검증(μ‚¬μš©μžμ˜ μ•„μ΄λ””μ˜ κΈΈμ΄λΌλ˜μ§€ μ •κ·œν‘œν˜„μ‹μ— λ§Œμ‘±ν•˜λŠ”μ§€μ— λŒ€ν•œ 검증 λ“±λ“±)κ³Ό λΉ„μ¦ˆλ‹ˆμŠ€ λ‘œμ§μ€ 보톡 Service λ‘œμ§μ— λ‹΄κ²¨μžˆμŠ΅λ‹ˆλ‹€. DB 쀑볡 체크 λ“± λΉ„μ¦ˆλ‹ˆμŠ€ λ‘œμ§μ€ μ„œλΉ„μŠ€μ— 두고, 이 λ°μ΄ν„°μ˜ μœ νš¨μ„± 검사λ₯Ό μŠ€ν”„λ§ λΆ€νŠΈμ—μ„œ μ œκ³΅ν•΄μ£ΌλŠ” Validation κΈ°λŠ₯을 μ΄μš©ν•˜λ©΄ μ†μ‰½κ²Œ 검증할 수 μžˆμ„ λΏλ”λŸ¬ μ„œλΉ„μŠ€μ—λŠ” 였직 핡심 λΉ„μ¦ˆλ‹ˆμŠ€ 둜직만 λ‘˜ 수 μžˆλŠ” μž₯점을 κ°€μ Έκ°ˆ 수 μžˆμ„ 것 κ°™μŠ΅λ‹ˆλ‹€. μ•„λž˜ μ‹€μŠ΅μ„ 톡해 μžμ„Έν•˜κ²Œ μ•Œμ•„λ³΄κ² μŠ΅λ‹ˆλ‹€.

κ°œλ°œν™˜κ²½

  • SpringBoot 2.7.9
  • JDK 11
  • Gradle

μ˜μ‘΄μ„± μΆ”κ°€

SpringBoot 2.3.0 μ΄μƒλΆ€ν„°λŠ” μ˜μ‘΄μ„±μ΄ ν¬ν•¨λ˜μ–΄ μžˆμ§€ μ•ŠκΈ° λ•Œλ¬Έμ— 직접 μΆ”κ°€ν•΄μ€˜μ•Ό ν•©λ‹ˆλ‹€.

implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'

Controller

@RestController
public class TestController {
	@PostMapping
	public Response saveAccount(@Valid @RequestBody SaveDto dto){  // ***
		// logic
	}
}

public class SaveDto {
	@NotBlank(min=6, message="μœ μ €λͺ…은 6자리 μ΄μƒμž…λ‹ˆλ‹€.")
	private String username;

	@NotBlank(min=8, message="λΉ„λ°€λ²ˆν˜ΈλŠ” 8자리 μ΄μƒμž…λ‹ˆλ‹€.")
	private String password;
}

μ»¨νŠΈλ‘€λŸ¬μ—μ„œ RequestBody에 λ°›λŠ” 객체에 @Valid μ–΄λ…Έν…Œμ΄μ…˜μ„ 뢙이면 λμž…λ‹ˆλ‹€. SaveDto의 ν”„λ‘œνΌν‹°μ— λŒ€ν•œ μ œμ•½μ‚¬ν•­μ€ 각 ν•„λ“œμ— μž‘μ„±ν•΄μ£Όμ‹œλ©΄ λ©λ‹ˆλ‹€.

@NotBlank 이 외에도 μ—¬λŸ¬ 검증을 ν•  수 μžˆμŠ΅λ‹ˆλ‹€. 더 λ‹€μ–‘ν•œ 검증을 ν•˜κ³  μ‹Άλ‹€λ©΄ μ—¬κΈ°λ₯Ό μ°Έμ‘°ν•΄μ£Όμ„Έμš”.

@Null null만 ν—ˆμš©
@NotNull null ν—ˆμš© X
””, “ “λŠ” ν—ˆμš©
@NotEmpty null, “” ν—ˆμš© X
” “λŠ” ν—ˆμš©
@NotBlank null, “”, “ “ ν—ˆμš© X
 

Java Bean Validation Basics | Baeldung

Learn the basics of Java Bean validation, the common annotations and how to trigger the validation process.

www.baeldung.com

@ExceptionHanlderλ₯Ό μ΄μš©ν•œ 응닡 처리

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Map<String, String> field(MethodArgumentNotValidException e) {
    HashMap<String, String> response = new HashMap<>();
    e.getFieldErrors().forEach(error -> {
        response.put(error.getField(), error.getDefaultMessage());
    });
    return response;
}

ν…ŒμŠ€νŠΈ

ν…ŒμŠ€νŠΈ μ½”λ“œλ₯Ό 톡해 μœ νš¨μ„± 검사λ₯Ό μ‹€νŒ¨ν–ˆμ„ λ•Œ μ˜¬λ°”λ₯Έ 응닡값이 μ˜€λŠ”μ§€ ν™•μΈν•΄λ³΄κ² μŠ΅λ‹ˆλ‹€.

@WebMvcTest
class ValidationControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void validationExceptionTest() throws Exception {
        // given
        String data = "{\"username\": \"user\", \"password\": \"pass\"}";

        // when & then
        mockMvc.perform(post("/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(data))
                .andDo(print())
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("username").exists())
                .andExpect(jsonPath("password").exists());
    }

}

μ •μƒμ μœΌλ‘œ ν…ŒμŠ€νŠΈκ°€ ν†΅κ³Όν•˜λŠ” 것을 확인할 수 μžˆμŠ΅λ‹ˆλ‹€! 

κ°μ‚¬ν•©λ‹ˆλ‹€.

REFERENCES

 

Validation in Spring Boot | Baeldung

Learn how to validate domain objects in Spring Boot using Hibernate Validator, the reference implementation of the Bean Validation framework.

www.baeldung.com

 

Java Bean Validation Basics | Baeldung

Learn the basics of Java Bean validation, the common annotations and how to trigger the validation process.

www.baeldung.com

λ°˜μ‘ν˜•