Springmvc-hibernate-validator
Spring MVC-Hibernate Validatorの例
次の例は、Spring Web MVCフレームワークを使用してフォームでエラー処理とバリデーターを使用する方法を示しています。 まず、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を順守します。
Step | Description |
---|---|
1 | Create a project with the name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes Student, StudentController and StudentValidator under the com.finddevguides package. |
3 | Create view files addStudent.jsp and result.jsp under the jsp sub-folder. |
4 | Download Hibernate Validator library Hibernate Validator. Extract hibernate-validator-5.3.4.Final.jar and required dependencies present under the required folder of the downloaded zip file. Put them in your CLASSPATH. |
5 | Create a properties file messages.properties under the SRC folder. |
6 | The final step is to create the content of the source and configuration files and export the application as explained below. |
Student.java
StudentController.java
messages.properties
ここで、キーは<Annotation>。<object-name>。<attribute>です。 値は表示されるメッセージです。
TestWeb-servlet.xml
ここでは、最初のサービスメソッド* student()について、ModelAndViewオブジェクトに「command」という名前の空白の *Studentobject> を渡しました。これは、Springフレームワークが、<command JSPファイルのform:form>タグ。 したがって、* student()メソッドが呼び出されると、 *addStudent.jsp ビューが返されます。
2番目のサービスメソッド* addStudent()は、 *HelloWeb/addStudent URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、サービスメソッドから「結果」ビューが返され、result.jspがレンダリングされます。 バリデーターを使用してエラーが生成された場合、同じビュー「addStudent」が返され、Springはビューの BindingResult からエラーメッセージを自動的に挿入します。
addStudent.jsp
ここでは、path = "*"で<form:errors/>タグを使用してエラーメッセージをレンダリングしています。 たとえば-
すべての入力検証のエラーメッセージを表示します。 <form:errors/>タグでpath = "name"を使用して、名前フィールドのエラーメッセージを表示しています。
たとえば-
名前と年齢フィールドの検証のエラーメッセージを表示します。
result.jsp
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 HelloWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください- http://localhost:8080/TestWeb/addStudent 。無効な値を入力した場合、次の画面が表示されます。