Validation
์ฃผ๋ก ์ฌ์ฉ์ ๋๋ ์๋ฒ์ ์์ฒญ (http request) ๋ด์ฉ์ ํ์ธํ๋ ๋จ๊ณ
Validation์ ์ข
๋ฅ
๋ฐ์ดํฐ ๊ฒ์ฆ
ํ์ ๋ฐ์ดํฐ์ ์กด์ฌ ์ ๋ฌด
๋ฌธ์์ด์ ๊ธธ์ด๋ ๋ฐ์ดํฐ ๊ฐ์ ๋ฒ์
email, ์ ์ฉ์นด๋ ๋ฒํธ ๋ฑ ํน์ ํ์์ ๋ง์ถ ๋ฐ์ดํฐ
๋น์ฆ๋์ค ๊ฒ์ฆ
์๋น์ค ์ ์ฑ ์ ๋ฐ๋ผ ๋ฐ์ดํฐ๋ฅผ ๊ฒ์ฆ
์) ๋ฐฐ๋ฌ์ฑ์ธ ๊ฒฝ์ฐ ๋ฐฐ๋ฌ ์์ฒญ์ ํ ๋ ํด๋น ์ฃผ๋ฌธ ๊ฑด์ด ๊ฒฐ์ ์๋ฃ ์ํ์ธ์ง ํ์ธ
๊ฒฝ์ฐ์ ๋ฐ๋ผ ์ธ๋ถ API ๋ฅผ ํธ์ถํ๊ฑฐ๋ DB ๋ฅผ ์กฐํํ์ฌ ๊ฒ์ฆํ๋ ๊ฒฝ์ฐ๋ ์กด์ฌ
Spring Validation
Java Bean Validation
public class MemberCreationRequest {
@NotBlank(message="์ด๋ฆ์ ์
๋ ฅํด์ฃผ์ธ์.")
@Size(max=64, message="์ด๋ฆ์ ์ต๋ ๊ธธ์ด๋ 64์ ์
๋๋ค.")
private String name;
@Min(0, "๋์ด๋ 0๋ณด๋ค ์ปค์ผ ํฉ๋๋ค.")
private int age;
@Email("์ด๋ฉ์ผ ํ์์ด ์๋ชป๋์์ต๋๋ค.")
private int email;
// the usual getters and setters...
}
์์ฒญ dto ์ ์ด๋ ธํ ์ด์ ์ผ๋ก ๋ช ์ ํ @RequestBody ์ @Valid ์ด๋ ธํ ์ด์ ์ ๋ฌ๊ฒ ๋๋ฉด, Java Bean Validation ์ด ์ํ๋๊ณ ๋ฌธ์ ๊ฐ ์์ ๋๋ง ๋ฉ์๋ ๋ด๋ถ๋ก ์ง์ ๋๋ค.
๊ฒ์ฆ ์ค ์คํจ๊ฐ ๋ฐ์ํ๋ฉด MethodArgumentNotValidException ๋ฐ์
@PostMapping(value = "/member")
public MemeberCreationResponse createMember(
@Valid @RequestBody final MemeberCreationRequest memeberCreationRequest) {
// member creation logics here...
}
Spring Validator Interface
public class Person {
private String name;
private int age;
// the usual getters and setters...
}
public class PersonValidator implements Validator {
/**
* This Validator validates only Person instances
*/
public boolean supports(Class clazz) {
return Person.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Person p = (Person) obj;
if (p.getAge() < 0) {
e.rejectValue("age", "negativevalue");
} else if (p.getAge() > 110) {
e.rejectValue("age", "too.darn.old");
}
}
}
Person์ด๋ผ๋ javaBean ๊ฐ์ฒด๊ฐ ์์ ๋, Validator ๋ฅผ ๊ตฌํํ PersonValidator ๋ฅผ ํตํด ๊ฒ์ฆํ๋ค.
supports
validator ๊ฐ ๋์ํ ์กฐ๊ฑด์ ์ ์. ์ฃผ๋ก class์ ํ์ ์ ๋น๊ตvalidate
๊ฒ์ฆ์ ์งํ
์ค๋ฌด ํ์ฉ
์์ฒญ dto ์์ Java Bean Validation ์ผ๋ก 1์ฐจ ๊ฒ์ฆ
๋ก์ง ์ด๊ธฐ์ ๋น์ฆ๋์ค ๊ฒ์ฆ ํ Custom Exception ์ฒ๋ฆฌ(ErrorCode, ErrorMessage)
Spring validator ์ฅ๋จ์
์ฅ์ : Java Bean Validation ์ ๋นํด ์กฐ๊ธ ๋ ๋ณต์กํ ๊ฒ์ฆ์ด ๊ฐ๋ฅ
๋จ์
Validation ์ ์ํํ๋ ์ฝ๋๋ฅผ ์ฐพ๊ธฐ๊ฐ ์ด๋ ต๋ค. (์๋์ ์ผ๋ก)
๋น์ฆ๋์ค ๊ฒ์ฆ ๋ก์ง์ ํํธํ ์ํ.
Last updated
Was this helpful?