public interface Validator {
boolean supports(Class<?> clazz); // ๊ฒ์ฆ ๊ฐ๋ฅ ์ฌ๋ถ ํ์ธ
void validate(Object target,Errors errors); // ๊ฒ์ฆ
}
์์ฒญ ํ๋ผ๋ฏธํฐ์ ๋ํด ๊ฒ์ฆ ๊ฐ๋ฅํ ๊ฐ์ฒด์ธ์ง ํ์ธํ๊ณ ๊ฒ์ฆํ๋ ์ญํ ์ ์ํํ๊ธฐ ์ํ ์ธํฐํ์ด์ค
๋ ๊ฐ์ง ๋ฐฉ๋ฒ์ ์ฌ์ฉํ ์ ์๋ค.
- ์ ์ญ ๋ฒ์์ ๋ํ ๊ฒ์ฆ์ ์ํ
- ์ผ๋ถ(์ปจํธ๋กค๋ฌ) ๋ฒ์์ ๋ํ ๊ฒ์ฆ์ ์ํ
Validator ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ๋ ํด๋์ค๋ฅผ ์ ์ธํ๋ค.
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
public class RegisterRequestValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
System.out.println("clazz: " + clazz.toString());
return true;
}
@Override
public void validate(Object target, Errors errors) {
System.out.println("target: " + target.toString());
System.out.println("errors: " + errors.toString());
}
}
Validator๋ฅผ ํตํด ์ ์ญ ๋ฒ์์ ๋ํ ๊ฒ์ฆ์ ์ํํ๊ธฐ ์ํด์ ๋ค์๊ณผ ๊ฐ์ด ์ด๋ฆ์ด ์ ํด์ง ๋น์ผ๋ก ๋ฑ๋กํ๋ค.
1. @Configuration ๋ด Bean์ผ๋ก ์ง์ ๋ฑ๋ก (getValidator ๋ฉ์๋๋ฅผ ์ค๋ฒ๋ผ์ด๋ฉํด์ผ ํจ)
@Override
public Validator getValidator() {
return new RegisterRequestValidator();
}
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.Valid;
@Controller
public class HelloController {
@GetMapping("/valid")
@ResponseBody
public String valid(@Valid ValidDto dto, Errors errors) {
if (errors.hasErrors()) System.out.println("has error!");
return "validation OK";
}
}
Validator๋ฅผ ํตํด ์ปจํธ๋กค๋ฌ ๋ฒ์์ ๋ํ ๊ฒ์ฆ์ ์ํํ๊ธฐ ์ํด์ @InitBinder ์ด๋ ธํ ์ด์ ์ ์ฌ์ฉํ๋ค.
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.Valid;
@Controller
public class HelloController {
@GetMapping("/valid")
@ResponseBody
public String valid(@Valid ValidDto dto, Errors errors) {
if (errors.hasErrors()) System.out.println("has error!");
return "validation OK";
}
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new RegisterRequestValidator());
}
}
ํด๋น ์ปจํธ๋กค๋ฌ ๋ด ๋ชจ๋ ๋ฉ์๋์ Validation์ด ์ ์ฉ๋๋ค.