◆ @Valid 어노테이션을 사용하기 위해 lib 추가 : javax.validation-1.0.0.GA.jar
◆ 스프링 3 MVC는 JSR 303의 @Valid 어노테이션과 스프링 프레임워크의 @InitBinder 어노테이션을 이용해서 Validator에 대한 직접적인 호출없이 스프링 프레임워크가 유효성 검사 코드를 실행하도록 할 수 있음
LoginVO.java
package sp.mvc.vo;
public class LoginVO { private String id; private String password; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "LoginVO [id=" + id + ", password=" + password + "]"; } } |
LoginValidator.java
package sp.mvc.validator;
import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator;
import sp.mvc.vo.LoginVO;
public class LoginValidator implements Validator {
@Override public boolean supports(Class<?> cla) { // TODO Auto-generated method stub System.out.println("--- LoginValidator.supports() ---"); return LoginVO.class.isAssignableFrom(cla); }
@Override public void validate(Object target, Errors errors) { // TODO Auto-generated method stub System.out.println("--- LoginValidator.validate() ---"); LoginVO loginVo = (LoginVO)target; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id", "required"); if(loginVo.getPassword() == null || loginVo.getPassword().trim().isEmpty()){ errors.rejectValue("password", "password.required"); } } } |
LoginController.java
package sp.mvc.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import sp.mvc.validator.LoginValidator; import sp.mvc.vo.LoginVO;
@Controller @RequestMapping(value="/login.sp") public class LoginController {
@RequestMapping(method=RequestMethod.GET) public String form(){ System.out.println("---- form ----"); return "login/loginForm"; } @RequestMapping(method=RequestMethod.POST) public String submit(@Valid LoginVO loginVo, BindingResult result, Model model){ System.out.println("login param : " + loginVo.toString()); if(result.hasErrors()){ System.out.println("---- validator count : " + result.getErrorCount() + "개"); //GET return "redirect:/login.sp"; } model.addAttribute("loginVo", loginVo); return "login/loginInfo"; } @InitBinder protected void initBinder(WebDataBinder binder){ binder.setValidator(new LoginValidator()); } } |
● 스프링은 @InitBinder 어노테이션이 적용된 메서드를 이용해서 폼과 커맨드 객체 사이의 매핑을 처리해주는 WebDataBinder를 초기화할 수 있도록 하고 있다. 이 메서드에서 WebDataBinder.setValidator() 메서드를 이용해서 커맨드 객체의 유효성 여부를 검사할 때 사용할 Validator를 설정하게 됨
● submit() 메서드 내부에서 Validator.validate() 메서드를 명시적으로 호출하지 않고 있음
main_config.xml
loginForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>로그인</title> </head> <body> <form action="login.sp" method="post"> <table border="1"> <tr> <td>ID</td> <td><input type="text" name="id" value=""/></td> </tr> <tr> <td>PW</td> <td><input type="password" name="password" value=""/></td> </tr> </table> <input type="submit" name="submit" value="전송"/> </form> </body> </html> |
loginInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>로그인</title> </head> <body> ${loginVo.id}님 반갑습니다. </body> </html> |
결과
요청 URL
http://localhost:8090/spring303/login.sp
---- form ---- --- LoginValidator.supports() --- --- LoginValidator.validate() --- login param : LoginVO [id=스누피123, password=123aaa] --- LoginValidator.supports() --- |
[참고자료] Spring 3.0 프로그래밍-최범균