sitelink1  
sitelink2  
sitelink3  
extra_vars6  
Spring MVC Validation 부분의 예는 jpetstore 의 유저 등록 부분인 AccountFormController 를 살펴보면 나와 있다.
AccountFormController 클래스는 SimpleFormController 를 확장한다. (AccountFormController extends SimpleFormController)
SimpleFormController 는 Spring MVC를 구현하는데에 매우 유용한 클래스이다. 이 클래스에 대한 활용은 추후에 좀 더 공부해야 할 필요가 있다.
단지 이 문서에서는 SimpleFormController 를 상속받아서 일부 Validation 체크가 이뤄지는 부분이 onBindAndValidate 메소드라는 사실만 알면 된다.

다음은 AccountFormController 클래스에 정의된 onBindAndValidate 메소드의 코드 내용이다.
·미리보기 | 소스복사·
  1. protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception {   
  2.   
  3.     AccountForm accountForm = (AccountForm) command;   
  4.     Account account = accountForm.getAccount();   
  5.   
  6.     if (request.getParameter("account.listOption") == null) {   
  7.         account.setListOption(false);   
  8.     }   
  9.     if (request.getParameter("account.bannerOption") == null) {   
  10.         account.setBannerOption(false);   
  11.     }   
  12.   
  13.     errors.setNestedPath("account");   
  14.     getValidator().validate(account, errors);   
  15.     errors.setNestedPath("");   
  16.   
  17.     if (accountForm.isNewAccount()) {   
  18.         account.setStatus("OK");   
  19.         ValidationUtils.rejectIfEmpty(errors, "account.userid""USER_ID_REQUIRED""User ID is required.");   
  20.         if (account.getPassword() == null || account.getPassword().length() < 1   
  21.             || !account.getPassword().equals(accountForm.getRepeatedPassword())) {   
  22.         errors.reject("PASSWORD_MISMATCH",   
  23.             "Passwords did not match or were not provided. Matching passwords are required.");   
  24.         }   
  25.     } else if (account.getPassword() != null && account.getPassword().length() > 0) {   
  26.         if (!account.getPassword().equals(accountForm.getRepeatedPassword())) {   
  27.             errors.reject("PASSWORD_MISMATCH""Passwords did not match. Matching passwords are required.");   
  28.         }   
  29.     }   
  30.   
  31. }  
위의 코드를 보면 중간쯤에 getValidator로 Validator객체를 요청하여 validation을 실행하는 것을 볼 수 있다.
요청된 클래스는 AccountValidator 클래스로써 Account 객체의 유효성을 체크한다.
AccountValidator 클래스는 Validator 인터페이스를 상속받고 있다. (AccountValidator implements Validator)
중요한 것은 Validator 인터페이스가 mvc에만 제한되어 있지 않다는 것이다.
Validator 인터페이스의 패키지를 보면 이러한 사실을 알 수 있다. (org.springframework.validation.Validator)
이는 유효성 체크가 웹계층과 연관이 없어야하고, 어떤 장소에 배치하기(localize) 쉬워야한다는 것과 어떠한 유효성 검사를 수행하고 싶은 개발자가 쉽게 플러그인 할 수 있도록 해야한다는 것을 의미한다.
그리고 Spring은 어플리케인션 모든 계층내에 기본적으로 사용할 수 있는 Validator 인터페이스를 제안하고 있다.

다음은 AccountValidator 클래스의 내용이다.
·미리보기 | 소스복사·
  1. public class AccountValidator implements Validator {   
  2.   
  3.     public boolean supports(Class clazz) {   
  4.         return Account.class.isAssignableFrom(clazz);   
  5.     }   
  6.   
  7.     public void validate(Object obj, Errors errors) {   
  8.         ValidationUtils.rejectIfEmpty(errors, "firstName""FIRST_NAME_REQUIRED""First name is required.");   
  9.         ValidationUtils.rejectIfEmpty(errors, "lastName""LAST_NAME_REQUIRED""Last name is required.");   
  10.         ValidationUtils.rejectIfEmpty(errors, "email""EMAIL_REQUIRED""Email address is required.");   
  11.         ValidationUtils.rejectIfEmpty(errors, "phone""PHONE_REQUIRED""Phone number is required.");   
  12.         ValidationUtils.rejectIfEmpty(errors, "address1""ADDRESS_REQUIRED""Address (1) is required.");   
  13.         ValidationUtils.rejectIfEmpty(errors, "city""CITY_REQUIRED""City is required.");   
  14.         ValidationUtils.rejectIfEmpty(errors, "state""STATE_REQUIRED""State is required.");   
  15.         ValidationUtils.rejectIfEmpty(errors, "zip""ZIP_REQUIRED""ZIP is required.");   
  16.         ValidationUtils.rejectIfEmpty(errors, "country""COUNTRY_REQUIRED""Country is required.");   
  17.     }   
  18. }  
코드에서는 대부분의 항목에 대한 유효성 체크를 하고 있지만 일부 항목에 대한 유효성 체크는 누락되어 있다. (Password, RepeatedPassword)
이 항목에 대한 유효성 체크는 신규가입인지, 개인정보수정 인지에 따라 분기하기 위해 컨트롤러의 onBindAndValidate 메소드내에서 직접적으로 구현하고 있는 것이다.
나머지 설정에 관련된 코드는 컨트롤러의 생성자 부분에 setValidateOnBinding(false); 코드와 servlet.xml 화일에 정의된 컨트롤러 설정부분이다.
컨트롤러 설정부분에서는 프로퍼티로 validator 객체를 셋팅하고 있다.
번호 제목 글쓴이 날짜 조회 수
공지 (확인전) [2021.03.12] Eclipse에서 Spring Boot로 JSP사용하기(Gradle) 황제낙엽 2023.12.23 0
공지 [작성중/인프런] 스프링부트 시큐리티 & JWT 강의 황제낙엽 2023.12.20 6
28 Spring Framework 에서 사용하는 annotation 황제낙엽 2024.01.17 1
27 Spring MVC configuration file 황제낙엽 2024.01.17 0
26 Spring, JSP, Gradle, Eclipse 환경 구축[2] - 샘플 프로젝트 file 황제낙엽 2023.12.24 0
25 Spring, JSP, Gradle, Eclipse 환경 구축[1] - 레퍼런스 조사 황제낙엽 2023.12.23 1
24 [Bard] Spring 과 Spring Boot의 차이 file 황제낙엽 2023.12.21 4
23 Spring 과 Spring Boot의 차이 file 황제낙엽 2020.05.26 202
22 Spring Boot에서의 RESTful API 모듈 file 황제낙엽 2020.04.16 216
21 Spring Security OAuth2.0 파헤치기 황제낙엽 2019.09.05 77
20 Spring Security OAuth2구현 file 황제낙엽 2019.09.05 462
19 Spring Security OAuth 황제낙엽 2019.09.05 435
18 [Spring3.1.1] Eclipse 에 Spring Framework 환경 구축하기 file 황제낙엽 2018.08.08 90
17 웹 개발의 변화와 스프링 황제낙엽 2008.03.19 132
16 Spring MVC 가 아닌 환경에서 Spring Pojo Bean 사용하기 (Pure Java App 또는 Servlet App) 황제낙엽 2009.10.22 233
15 프로젝트의 기본이 되는 Logging, Exception 처리 전략 황제낙엽 2007.01.30 85
14 SimpleFormController 정리 황제낙엽 2007.09.19 206
13 스프링 개발팁 황제낙엽 2007.08.17 223
» 유효성체크 (org.springframework.validation.Validator) 황제낙엽 2007.08.17 129
11 CSS와 XHTML을 사용한 효율적인 View 개발 전략 황제낙엽 2007.01.30 104
10 Spring framework jpetstore 샘플 분석기 - (6) jpetstore 예제로 살펴보는 Spring MVC와 iBatis 연동 황제낙엽 2007.01.18 48
9 Spring framework jpetstore 샘플 분석기 - (5) jpetstore 에서의 InternalResourceViewResolver 황제낙엽 2007.01.18 17