스프링

 

13. [동영상 강좌] - 박재성 (스프링) - Server Side Validation 1 유효성

 

[Spring 3 - @MVC] 모델 바인딩과 검증 #4 - Validator 와 BindingResults, Errors

 

pom.xml


		<!-- JSR 303 with Hibernate Validator -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>5.0.1.Final</version>
		</dependency>

 

 

root-context.xml


	
<bean id="messageSource"class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="messages" />
		<property name="defaultEncoding" value="UTF-8" />
</bean>

 

 

messages.properties

Size.user.userId = 사용자 {0} 는 {2}보다 크고 {1}보다 작아야 합니다.
NotEmpty.user.userId = 사용자 {0} 는 필수값 입니다.
Min.user.userId = 사용자 아이디 값의 길이는 {1} 보다 커야 합니다.
Max.user.userId = 사용자 아이디 값의 길이는 {1} 보다 작아야 합니다.


Size.user.password = 사용자 {0} 는 {2}보다 크고 {1}보다 작아야 합니다.
Min.user.password = 사용자 패스워드 값의 길이는 {1} 보다 커야 합니다.
Max.user.password = 사용자 패스워드 값의 길이는 {1} 보다 작아야 합니다.

NotEmpty.user.password = 사용자 {0} 는 필수값 입니다.
NotEmpty.user.name = 사용자 {0} 은 필수값 입니다.


NotEmpty.user.email=이메일을 입력하세요.
Email.user.email=이메일 형식에 맞지 않습니다.



 

 

User

public class User {
	
	@NotNull @Min(4) @Max(12)
	private String userId; 
	
	@NotNull @Min(4) @Max(12)
	private String password;
	
	@NotNull
	private	String name;
	
	@NotEmpty @Email
	private String email;
    
    
	public User() {

	}
	public User(String userId, String password, String name, String email) {
		super();
		this.userId = userId;
		this.password = password;
		this.name = name;
		this.email = email;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getPassword() {
		return password;
	}

}

 

class UserController 

package com.java.web;


import org.slf4j.Logger;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.java.dao.users.UserDao;
import com.java.dto.User;
import javax.validation.constraints.*;

import java.util.List;

import javax.validation.Valid;


@Controller
@RequestMapping("/users")
public class UserController {
	
	private static final Logger logger=LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserDao userDao;
	
	@RequestMapping("/form")
	public String form(Model model){
		logger.debug("User : {} " , "test");
		model.addAttribute("user" , new User());
		return "users/form";
	}
	
	@RequestMapping(value="", method=RequestMethod.POST)
	public String create(@Valid User user, BindingResult bindingResult ){
		logger.debug("User : {} " , user);
		if(bindingResult.hasErrors()){
			logger.debug("Binding Result has error!");
			List<ObjectError> errors=bindingResult.getAllErrors();
			for(ObjectError error : errors){
				logger.debug("error : {}, {}", error.getCode(), error.getDefaultMessage());
			}
			
			return "users/form";
		}
		userDao.create(user);
		logger.debug("Database : {} " , userDao.findById(user.getUserId()));
		return "redirect:/";
	}
	
	
}




 

 

form.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html >
<html lang="ko">
<head>
    <%@ include file="../include/header.jspf" %>
</head>
<body>
<%@ include file="../include/navigation.jspf" %>

<div class="container" id="main">
    <div class="col-md-6 col-md-offset-3">
        <div class="panel panel-default content-main">
          
          <form:form name="question" method="post" action="/users"    modelAttribute="user">
                <div class="form-group">
                    <label for="userId">사용자 아이디</label>
                    <!-- <input class="form-control" id="userId" name="userId" placeholder="User ID"> -->
                    <form:input path="userId" cssClass="form-control" />
                    <form:errors path="userId" />
                </div>
                <div class="form-group">
                    <label for="password">비밀번호</label>
                  <!--   <input type="password" class="form-control" id="password" name="password" placeholder="Password"> -->
                    <form:password path="password" cssClass="form-control"/>
                    <form:errors path="password" />
                </div>
                <div class="form-group">
                    <label for="name">이름</label>
                  <!--   <input class="form-control" id="name" name="name" placeholder="Name"> -->
                    <form:input path="name" cssClass="form-control"/>
                    <form:errors path="name" />
                </div>
                <div class="form-group">
                    <label for="email">이메일</label>
                   <!--  <input type="email" class="form-control" id="email" name="email" placeholder="Email"> -->
                    <form:input path="email" cssClass="form-control"/>
                    <form:errors path="email" />
                </div>
                <button type="submit" class="btn btn-success clearfix pull-right">회원가입</button>
                <div class="clearfix" />
            
            </form:form>
        </div>
    </div>
</div>

<%@ include file="../include/footer.jspf" %>
</body>
</html>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

비록 때리지는 않았다고 해도, 남에게 손가락질을 하는 사람은 악독한 사람이다. -탈무드

댓글 ( 4)

댓글 남기기

작성