@Valid와 @InitBinder 어노테이션을 이용한 검증
스프링 MVC는 JSR 303의 @Valid 어노테이션과 스프링 프레임워크의 @InitBinder 어노테이션을 이용해서 스프링 프레임워크가 유효성 검사 코드를 실행하도록 할 수 있다. 다음 예시를 보자.
@Controller
@RequestMapping("/auth/login")
public class LoginController {
@RequestMapping(method = RequestMethod.POST)
public String login(@Valid LoginCommand loginCommand, Errors errors,
HttpServletRequest request) {
if (errors.hasErrors()) {
return LOGIN_FORM;
}
// 이하 생략
...
}
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new LoginCommandValidator());
}
// 이하 생략
...
}
위 코드에서 커맨드 객체 파라미터에 @Valid 어노테이션을 적용하고, login() 메서드 내부에서 Validator 객체의 validate() 메서드를 호출하고 있지 않다. 단지 Errors 파라미터를 이용해서 에러가 존재할 경우 폼을 다시 보여주도록 하고 있다.
어떤 Validator가 커맨드 객체를 검증할지의 여부는 initBinder() 메서드를 통해서 결정된다. 스프링은 @InitBinder 어노테이션이 적용된 메서드를 이용해서 폼과 커맨드 객체 사이의 매핑을 처리해주는 WebDataBinder를 초기화할 수 있도록 하고 있다. 이 메서드에서 WebDataBinder.setValidator() 메서드를 통해 커맨드 객체의 유효성 여부를 검사할 때 사용할 Validator를 설정하게 된다.
글로벌 Validator와 컨트롤러 Validator
글로벌 Validator를 사용하면 한 개의 Validator를 이용해서 모든 커맨드 객체를 검증할 수 있다. 적용 방법은 다음과 같다.
<mvc:annotation-driven validator="validator"/>
<bean id="validator" class="custom.CommonValidator" />
글로벌 Validator의 supports() 메서드가 false를 리턴하면 글로벌 Validator는 커맨드 객체를 검증하지 않는다.
글로벌 Validator를 사용하지 않고 다른 Validator를 사용하려면 앞서 본 코드와 같이 @InitBinder 어노테이션이 적용된 메서드에서 WebDataBinder의 setValidator() 메서드를 이용하면 된다.
@InitBinder
protected void initBinder(WebDataBinder binder) {
// 글로벌 Validator가 아닌 다른 Validator 사용
binder.setValidator(new LoginCommandValidator());
}
글로벌 Validator를 사용하면서 컨트롤러를 위한 Validator를 추가로 사용하려면 setValidator() 대신 addValidator() 메서드를 사용하면 된다.
@InitBinder
protected void initBinder(WebDataBinder binder) {
// 글로벌 Validator와 함께 사용
binder.addValidator(new LoginCommandValidator());
}
@EnableWebMvc 어노테이션을 사용했다면, 다음과 같이 WebMvcConfigurerAdapter를 상속받은 @Configuration 클래스에서 글로벌 Validator 객체를 생성하도록 getValidator() 메서드를 재정의한다.
@Configuration
@EnableWebMvc
public class SampleConfig extends WebMvcConfigurerAdapter {
@Override
public Validator getValidator() {
return new CommonValidator();
}
// 이하 생략
...
}
Reference
- 웹 개발자를 위한 Spring 4.0 프로그래밍 (최범균 저)
'Spring' 카테고리의 다른 글
| [Spring] 스프링 MVC(11) - @ExceptionHandler, @ControllerAdvice, @ResponseStatus 어노테이션 (0) | 2022.03.16 |
|---|---|
| [Spring] 스프링 MVC(10) - HttpSession과 @SessionAttributes 어노테이션 (0) | 2022.03.16 |
| [Spring] 스프링 MVC(8) - Validator와 Errors/BindingResult (0) | 2022.03.14 |
| [Spring] 스프링 MVC(7) - 커맨드 객체와 @ModelAttribute 어노테이션 (0) | 2022.03.13 |
| [Spring] 스프링 MVC(6) - @RequestParam 어노테이션 (0) | 2022.03.13 |