■ Validator : org.springframework.validation.Validator 인터페이스는 객체를 검증할 때 사용
◆ Validator 인터페이스의 메서드
boolean supports(Class<?> clazz) |
Validator가 해당 클래스에 대한 값 검증을 지원하는 지의 여부를 리턴 |
void validate(Object target, Errors errors) |
target 객체에 대한 검증을 실행. 검증 결과에 문제가 있을 경우 errors 객체에 에러 정보 저장 |
◆ 커맨드 객체에 검증코드 추가 방법
● @RequestMapping 어노테이션 메서드에서 커맨드 객체 다음 파라미터로 BindingResult 타입이나 Errors 타입의 파라미터 추가
● 메서드 내에서 Validator 객체를 생성 후 validate() 메서드에 커맨드 객체와 BindingResult 또는 Errors 타입의 파라미터를 전달
● Errors.hasErrors() 메서드를 이용해서 에러가 존재하는 지 확인하고, 에러가 존재할 경우 알맞은 처리를 수행
UserVO.java
package sp.mvc.vo;
public class UserVO { |
UserVoValidator.java
package sp.mvc.validator; import org.springframework.validation.Errors; import sp.mvc.vo.UserVO;
public class UserVoValidator implements Validator { @Override
@Override
} |
UserController.java
package sp.mvc.controller; import javax.servlet.http.HttpServletRequest; import sp.mvc.validator.UserVoValidator;
@Controller |
main_config.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" <context:annotation-config/>
|
userForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" <form action="userForm.sp" method="post"> |
userInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" <table border="1"> </body> |
결과 - [에러가 없는 경우]
요청 URL http://localhost:8090/spring303/userForm.sp
---- @ModelAttribute ---- |
결과 - [에러가 존재하는 경우]
요청 URL http://localhost:8090/spring303/userForm.sp
---- @ModelAttribute ---- |
[참고자료] Spring 3.0 프로그래밍-최범균
'프로그램 > Spring 3.0' 카테고리의 다른 글
ValidationUtils 클래스를 이용한 폼 값 검증 (0) | 2012.05.21 |
---|---|
Errors 인터페이스와 BindingResult 인터페이스 (0) | 2012.05.21 |
@PathVariable 어노테이션과 Ant 경로 패턴 (0) | 2012.05.17 |
전체 경로와 서블릿 기반 경로 매칭 (0) | 2012.05.17 |
@ModelAttribute 어노테이션 (2) | 2012.05.16 |