Spring 3 MVCとJSR303 @正当な例
Spring 3では、 “http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-annotation-driven[mvc:annotation-driven]を有効にできます。 “クラスパス上のJSR 303バリデーターフレームワークがあれば、` @ Valid`アノテーションを使用してhttp://jcp.org/ja/jsr/detail?id=303[JSR303 bean validation]をサポートします。
このチュートリアルでは、HTMLフォームでBeanの検証を実行するために、HibernateバリデーターとSpring MVCを `@ Valid`アノテーションを使って統合する方法を説明します。
使用される技術:
-
Spring 3.0.5.RELEASE
-
Hibernate Validator 4.2.0.Final
-
JDK 1.6
-
Eclipse 3.6
-
Maven 3
プロジェクトの依存関係
HibernateバリデータはJBossの公開リポジトリから入手できます。
<repositories> <repository> <id>JBoss repository</id> <url>http://repository.jboss.org/nexus/content/groups/public/</url> </repository> </repositories> <properties> <spring.version>3.0.5.RELEASE</spring.version> </properties> <dependencies> <!-- Spring 3 dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- Hibernate Validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.2.0.Final</version> </dependency> </dependencies>
2. JSR303 Bean検証
単純なPOJOで、Hibernateバリデータアノテーションでアノテーションされています。
-
注意** +詳細な説明については、http://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html/[Hibernate validator documentation]を参照してください。
package com.mkyong.common.model; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range; public class Customer { @NotEmpty//make sure name is not empty String name; @Range(min = 1, max = 150)//age need between 1 and 150 int age; //getter and setter methods }
3.コントローラ@Valid
バリデーションを有効にするには、「@ Valid」を介して「JSR注釈付きモデルオブジェクト」に注釈を付けるだけです。つまり、他のものは通常のSpring MVCのフォーム処理です。
package com.mkyong.common.controller; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.mkyong.common.model.Customer; @Controller @RequestMapping("/customer") public class SignUpController { @RequestMapping(value = "/signup", method = RequestMethod.POST) public String addCustomer(@Valid Customer customer, BindingResult result) { if (result.hasErrors()) { return "SignUpForm"; } else { return "Done"; } } @RequestMapping(method = RequestMethod.GET) public String displayCustomerForm(ModelMap model) { model.addAttribute("customer", new Customer()); return "SignUpForm"; } }
4.エラーメッセージ
デフォルトでは、検証に失敗した場合。
-
`@ NotEmpty`は”空ではないかもしれません “と表示します
-
`@ Range`は” 1と150の間でなければならない “と表示する
簡単に上書きし、「キー」とメッセージでプロパティを作成することができます。
どんな@nonotationがどのキーにバインドされているかを知るには、単に `BindingResult result`の中でデバッグして値を見るだけです。通常、キーは ”
@ Annotation Name.object.fieldname
“です。
ファイル:messages.properties
NotEmpty.customer.name = Name is required! Range.customer.age = Age value must be between 1 and 150
5. mvc:アノテーション駆動型
Spring MVCが
@ Valid`を介してJSR303バリデータをサポートするように
`mvc:annotation-driven`を有効にし、プロパティファイルもバインドします。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.mkyong.common.controller"/> <!-- support JSR303 annotation if JSR 303 validation present on classpath --> <mvc:annotation-driven/> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <!-- bind your messages.properties --> <bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource"> <property name="basename" value="messages"/> </bean> </beans>
6. JSPページ
最後の1つは、Springフォームのタグライブラリを持つ通常のJSPページです。
File:SignUpForm.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <html> <head> <style> .error { color: #ff0000; } .errorblock { color: #000; background-color: #ffEEEE; border: 3px solid #ff0000; padding: 8px; margin: 16px; } </style> </head> <body> <h2>Customer SignUp Form - JSR303 @Valid example</h2> <form:form method="POST" commandName="customer" action="customer/signup"> <form:errors path="** " cssClass="errorblock" element="div"/> <table> <tr> <td>Customer Name :</td> <td><form:input path="name"/></td> <td><form:errors path="name" cssClass="error"/></td> </tr> <tr> <td>Customer Age :</td> <td><form:input path="age"/></td> <td><form:errors path="age" cssClass="error"/></td> </tr> <tr> <td colspan="3"><input type="submit"/></td> </tr> </table> </form:form> </body> </html>
File:Done.jsp
<html> <body> <h2>Done</h2> </body> </html>
6.デモ
URL:http://localhost:8080/SpringMVC/customer
– 顧客フォームページ。名前と年齢の2つのテキストボックス。
URL:http://localhost:8080/SpringMVC/customer/signup
– フォームに記入せずに「送信」ボタンをクリックすると、カスタマイズされた検証エラーメッセージが表示されます。
ソースコードをダウンロードする
ダウンロードする –
SpringMVC-Bean-Validation-JSR303-Example2.zip
(9 KB)