■ 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 {
 private String userName;
 private String address;
 private String fruit;
 
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 public String getFruit() {
  return fruit;
 }
 public void setFruit(String fruit) {
  this.fruit = fruit;
 }
 
 @Override
 public String toString() {
  return "UserVO [userName=" + userName + ", address=" + address + ", fruit=" + fruit + "]";
 }
}

 

UserVoValidator.java

package sp.mvc.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import sp.mvc.vo.UserVO;

 

public class UserVoValidator implements Validator {

 @Override
 public boolean supports(Class<?> clazz) {
  // TODO Auto-generated method stub
  System.out.println("--- UserVoValidator.supports() ---");
  return UserVO.class.isAssignableFrom(clazz);
 }

 

 @Override
 public void validate(Object target, Errors errors) {
  // TODO Auto-generated method stub
  System.out.println("--- UserVoValidator.validate() ---");
  
  UserVO userVo = (UserVO)target;
  
  if(userVo.getUserName() == null || userVo.getUserName().trim().isEmpty()){
   errors.rejectValue("id", "required");
  }
  
  if(userVo.getAddress() == null || userVo.getAddress().trim().isEmpty()){
   errors.rejectValue("address", "required");
  }
 }

 

}

 

UserController.java

package sp.mvc.controller;

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import sp.mvc.validator.UserVoValidator;
import sp.mvc.vo.UserVO;

 

@Controller
@RequestMapping("/userForm.sp")

public class UserController {
 
 @ModelAttribute("userVo")
 public UserVO initForm(HttpServletRequest req){
  System.out.println("---- @ModelAttribute ----");
  
  if(req.getMethod().equalsIgnoreCase("GET")){
   System.out.println("---- @ModelAttribute : GET ----");
   
   UserVO userVo = new UserVO();
   userVo.setUserName("input name");
   userVo.setAddress("input address");
   userVo.setFruit("input fruit");
   
   return userVo;
  }else{
   System.out.println("---- @ModelAttribute : POST ----");
   
   return new UserVO();
  }  
 }
 
 
 @RequestMapping(method=RequestMethod.GET)
 public String userForm(){
  System.out.println("---- UserController.userForm() ----");
  
  return "user/userForm";
 }

 
 @RequestMapping(method=RequestMethod.POST)
 public String userSave(@ModelAttribute("userVo") UserVO userVo, BindingResult result){
  System.out.println("---- UserController.userSave() ----");
  System.out.println("userInfo : " + userVo.toString());
  
  UserVoValidator userVoValidator = new UserVoValidator();
  userVoValidator.validate(userVo, result);
  
  if(result.hasErrors()){
   System.out.println("---- validator : " + result.getErrorCount()+ "개 errors ----");
   
   //다시 GET 방식으로 호출
   return "redirect:/userForm.sp";
  }
   
  System.out.println("---- validator : no errors ----");
  return "user/userInfo";

 }
 
}

 

main_config.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <context:annotation-config/>
 <context:component-scan base-package="sp.mvc.controller"/>


 <!-- bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" p:alwaysUseFullPath="true"/ -->
 <!-- bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" p:alwaysUseFullPath="true"/ --> 
  
 <!-- ViewResolver 설정 -->
 <bean id="internalResource" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="jsp/"></property>
  <property name="suffix" value=".jsp"></property>
 </bean>

 
 <!-- 각종 bean 설정 -->

 
</beans>

 

userForm.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>

<form action="userForm.sp" method="post">
 <table border="1">
  <tr>
   <td>이름</td>
   <td><input type="text" name="userName" value="${userVo.userName}"/></td>
  </tr>
  <tr>
   <td>주소</td>
   <td><input type="text" name="address" value="${userVo.address}"/></td>
  </tr>
 </table> 
 <input type="submit" name="submit" value="전송"/>
</form>
</body>
</html>

 

userInfo.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>

 <table border="1">
  <tr>
   <td>이름</td>
   <td>${userVo.userName}</td>
  </tr>
  <tr>
   <td>주소</td>
   <td>${userVo.address}</td>
  </tr>
 </table>

</body>
</html>

 

 

결과 - [에러가 없는 경우]

요청 URL

   http://localhost:8090/spring303/userForm.sp

 

 

 

 

---- @ModelAttribute ----
---- @ModelAttribute : GET ----
---- UserController.userForm() ----
---- @ModelAttribute ----
---- @ModelAttribute : POST ----
---- UserController.userSave() ----
userInfo : UserVO [userName=스누피, address=제주도 321, fruit=null]
--- UserVoValidator.validate() ---
---- validator : no errors ----

 

결과 - [에러가 존재하는 경우]

요청 URL

   http://localhost:8090/spring303/userForm.sp

 

 

 

 

---- @ModelAttribute ----
---- @ModelAttribute : GET ----
---- UserController.userForm() ----
---- @ModelAttribute ----
---- @ModelAttribute : POST ----
---- UserController.userSave() ----
userInfo : UserVO [userName=스누피, address=, fruit=null]
--- UserVoValidator.validate() ---
---- validator : 1개 errors ----

---- @ModelAttribute ----
---- @ModelAttribute : GET ----
---- UserController.userForm() ----

 

 

 

[참고자료] Spring 3.0 프로그래밍-최범균

 

+ Recent posts