note

Spring 유효성 체크 본문

JSP/Spring

Spring 유효성 체크

투한 2012. 3. 5. 15:32































dispatcher-servlet.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">

	<!-- 커맨드 객체 초기화 -->
	<bean id="madvirus.spring.chap06.controller.CreateAccountController" />
	
	<!-- View 글로벌 설정 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	<!-- 리소스 번들 지정 -->
	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
	 <property name="basenames">
	 	<list>
	 		<value>message.validation</value>
	 	</list>
	 </property>
	</bean>
</beans>




madvirus.spring.chap06.validator/MemberInfoValidator.java
package madvirus.spring.chap06.validator;

import madvirus.spring.chap06.model.Address;
import madvirus.spring.chap06.model.MemberInfo;

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

public class MemberInfoValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return MemberInfo.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		MemberInfo memberInfo = (MemberInfo) target;
		if(memberInfo.getId() == null || memberInfo.getId().trim().isEmpty()){
			errors.rejectValue("id","required");
		}
		if(memberInfo.getName() == null || memberInfo.getName().trim().isEmpty()){
			errors.rejectValue("name","required");
		}
		Address address =memberInfo.getAddress();
		if(address == null){
			errors.rejectValue("address","required");
		}
		if(address != null){
			errors.pushNestedPath("address");
			try{
				if(address.getZipcode() == null || address.getZipcode().trim().isEmpty()){
					errors.rejectValue("zipcode","required");
				}
				if(address.getAddress1() == null || address.getAddress1().trim().isEmpty()){
					errors.rejectValue("address1","required");
				}

			}finally{
				errors.popNestedPath();
			}
		}

	}
}





madvirus.spring.chap06.model/Address.java
package madvirus.spring.chap06.model;

public class Address {
	
	private String zipcode;
	private String address1;
	private String address2;
	
	public String getZipcode() {
		return zipcode;
	}
	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}
	public String getAddress1() {
		return address1;
	}
	public void setAddress1(String address1) {
		this.address1 = address1;
	}
	public String getAddress2() {
		return address2;
	}
	public void setAddress2(String address2) {
		this.address2 = address2;
	}
}





madvirus.spring.chap06.model/MemberInfo.java
package madvirus.spring.chap06.model;

public class MemberInfo {

	private String id;
	private String name;
	private Address address;

	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}	
}






message/validation.properties
required=필수항목입니다.
invalidIdOrPassword.loginCommand=아이디({0})와 암호가 일치하지 않습니다.
required.loginCommand.userId=사용자 아이디는 필수 항목입니다.
required.password=암호는 필수 항목입니다.
typeMisamatch.from=시작일 값 형식은 yyyy-MM-dd 여야 합니다
typeMisamatch.to=종료일 값 형식은 yyyy-MM-dd 여야 합니다.




madvirus.spring.chap06.controller/CreateAccountController.java
package madvirus.spring.chap06.controller;

import javax.servlet.http.HttpServletRequest;

import madvirus.spring.chap06.model.Address;
import madvirus.spring.chap06.model.MemberInfo;
import madvirus.spring.chap06.validator.MemberInfoValidator;

import org.springframework.stereotype.Controller;
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;

@Controller
@RequestMapping("/account/create.do")
public class CreateAccountController {

	@ModelAttribute("command")
	public MemberInfo formBacking(HttpServletRequest request) {
		if (request.getMethod().equalsIgnoreCase("GET")) {
			MemberInfo mi = new MemberInfo();
			Address address = new Address();
			address.setZipcode(AutoDetectZipcode(request.getRemoteAddr()));

			mi.setAddress(address);
			return mi;
		} else {
			return new MemberInfo();
		}
	}

	private String AutoDetectZipcode(String remoteAddr) {
		return "000000";
	}

	@RequestMapping(method = RequestMethod.GET)
	public String form() {
		return "account/creationForm";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String submit(@ModelAttribute("command") MemberInfo memberInfo,
			BindingResult result) {
		new MemberInfoValidator().validate(memberInfo, result);

		if (result.hasErrors()) {
			return "account/creationForm";
		}
		return "account/created";
	}
}


CreateAccountController

equalsIgnoreCase
대소문자 구별없이 조건 체크함 (영문만 가능함)





view/account/created.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>계정 생성</title>
</head>
<body>
계정 생성됨
<ul>
 <li>아이디: ${command.id}</li>
 <li>이름: ${command.name}</li>
 <li>우편번호: ${command.address.zipcode}</li>
 <li>주소: ${command.address.address1} ${command.address.address2}</li>
</ul>
</body>
</html>




view/account/creationForm.jsp 
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>계정 생성</title>
</head>
<body>
<spring:hasBindErrors name="command" />
<form:errors path="command" />
<form method="post">
	아이디: <input type="text" name="id" value="${command.id}" />
	<form:errors path="command.id" />
	<br/>
	이름: <input type="text" name="name" value="${command.name}" />
	<form:errors path="command.name" />
	<br/>
	우편번호: <input type="text" name="address.zipcode" value="${command.address.zipcode}" />
	<form:errors path="command.address.zipcode" />
	<br/>
	주소1: <input type="text" name="address.address1" value="${command.address.address1}" />
	<form:errors path="command.address.address1" />
	<br/>
	주소2: <input type="text" name="address.address2" value="${command.address.address2}" />
	<form:errors path="command.address.address2" />
	<br/>
	<input type="submit" />
</form>
</body>
</html>


Spring에서 제공하는 커스텀 태그 사용

<spring:hasBindErrors name="command" />

<form:errors path="command" />
에러 처리를 할 수 있는 기본적인 셋팅