Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
Tags
- JSP
- Menu
- mybatis
- HTML
- Java
- Eclips
- 오버로딩
- JavaScript
- AWT
- 전화걸기
- 안드로이드
- 국제화
- 에러페이지
- paint
- 어노테이션
- 이클립스
- Graphic
- Spring
- 생성자
- Android
- oracle
- 배열
- 예외처리
- 기본
- layout
- 클래스
- 메서드
- OGNL
- 메소드
- struts2
Archives
- Today
- Total
note
Spring 유효성 체크 본문
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" />에러 처리를 할 수 있는 기본적인 셋팅
'JSP > Spring' 카테고리의 다른 글
| @PathVariable 을 이용한 주소 확장기능 (0) | 2012.03.06 |
|---|---|
| Spring 요청 URI 매칭 (0) | 2012.03.05 |
| 뷰에 모델 데이터 전달하기 (0) | 2012.03.05 |
| Spring 컨트롤러 메서드의 리턴 타입 (0) | 2012.03.05 |
| @RequestHeader 어노테이션을 이용한 헤더 매핑 (0) | 2012.03.05 |