더북(TheBook)

예제에서는 컨트롤러 메서드의 @ModelAttribute 매개변수에 @Valid를 선언합니다.

그리고 생성된 스프링 Validator 인터페이스의 구현체를 해당 컨트롤러 내의 @InitBinder가 선언된 메서드에 설정합니다. 그러면 커맨드 객체를 바인딩하는 WebDataBinder는 @InitBinder 메서드에서 등록된 Validator를 사용하여 모델을 검증하고, 그 결과를 BindingResult에 넣어 전달합니다. 따라서 메서드의 매개변수로 전달받는 BindingResult에는 이미 PersonValidator로 검증한 결과가 담깁니다.

webpage13_03.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Validation</title>
</head>
<body>
    <h3>유효성 검사</h3>
    <form:form modelAttribute="person" method="post">
        <p>이름:<form:input path="name"/> <form:errors path="name"/>
        <p>나이:<form:input path="age"/> <form:errors path="age"/>
        <p>이메일:<form:input path="email"/> <form:errors path="email"/>
        <p><input type="submit" value="확인"/>
    </form:form>
</body>
</html>

▲ 그림 13-8 실행 결과

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.