'2012.03.23 追記
このブログで扱っているSpringMVCのバージョンは2.5で、情報が古くなっています。
現状、アノテーションを使用してかなり柔軟で使いやすくなっています。
この記事を削除することはしませんが、最新の情報を検索されることをお勧めします。
---------------------------
Springでは妥当性チェックの方法をいくつか用意しています。
主には以下の2つかと思います。
①Vallidatorクラスを継承する方法
②Spring Modulesを使用する方法
ここでは、①の方法を見てみます。
②の方法は別の記事で見てみようと思います。(・SpringModulesの機能について )
ほとんどの場合、WEBであれば②の方法で問題ないと思いますが、何か特殊なチェックをする場合は①の方法も知っておいた方がいいでしょう。
では、早速見てみましょう。
ここではValidatorの説明をメインとしたいため、Validator以外はあまり意味のない設定をしているので
Validator以外は気にせずに見てみてください。
【Validatorクラス】
妥当性チェックをします。
チェックボックスがチェックされているときにメッセージがnullならエラーとします。
Validatorクラスがチェックできるのは1つのオブジェクトだけです。
それを規定しているのがsupportsメソッドです。
Spring設定ファイルの読み込み時にこのメソッドをチェックしていて、falseのときエラーになります。
package validator; import org.springframework.util.StringUtils; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import business.domain.CmdTest; public class CmdTestValidator implements Validator { @Override /** * 対象のオブジェクトがこのクラスが対象とするクラスかをチェックする。 */ public boolean supports(Class clazz) { return CmdTest.class.isAssignableFrom(clazz); } @Override /** * 妥当性チェックをする。 * ここでは、displayチェックがされたときに * messageに値が入っているかをチェックします。 */ public void validate(Object obj, Errors errors) { CmdTest cmd = (CmdTest)obj; if(cmd.isDisplay()){ if(!StringUtils.hasLength(cmd.getMessage())){ errors.rejectValue("message", "error.required", "メッセージは必須です"); } } } }
【Spring設定ファイル(test-servlet.xml)】
ここではSimpleFormControllerを使用します。
submitすると同じ画面に遷移するようにします。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd "> <!-- メッセージリソースの設定。 bean名はmessageSourceにする必要があります。 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages"/> </bean> <!-- HandlerMapping --> <bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/input.html">validatorTestInputController</prop> </props> </property> </bean> <!-- サンプルController --> <bean id="validatorTestInputController" class="org.springframework.web.servlet.mvc.SimpleFormController"> <property name="commandClass" value="business.domain.CmdTest" /> <property name="formView" value="/WEB-INF/jsp/input.jsp" /> <property name="successView" value="/WEB-INF/jsp/input.jsp" /> <property name="validator" > <bean class="validator.CmdTestValidator"/> </property> </bean> </beans>
【オブジェクト(CmdTest.java)】
ここで使用しているオブジェクト(POJO)です。
StrutsでいえばActionFormに当たるものです。
上記のSpringの設定はこのクラスに対してチェックをかけるように設定しています。
package business.domain;
public class CmdTest {
private boolean display = false;
private String message;
public boolean isDisplay() {
return display;
}
public void setDisplay(boolean display) {
this.display = display;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
【View(input.jsp)】
値を入力してボタンを押すとエラーかどうかを表示してくれます。
<%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%
>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags
" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form
" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd ">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>入力テスト</title>
</head>
<body>
validatorControllerテスト<br>
<br>
<form:form method="post" >
<form:errors path="*" cssStyle="font-weight: bold; color: red;"></form:errors>
<br><br>
<form:checkbox path="display"/>
メッセージを表示します<br>
<form:input path="message"/>
<input type="submit" value="入力">
</form:form>
</body>
</html>
【表示画面】
http://localhost:8080/test/input.html
【説明】
Viewを見てみてください。
目新しい、formタグが使われていますね。
これは、オブジェクト(ここではCmdTestクラス)と連動して値を入れてくれたりエラーメッセージを出力してくれるタグです。
とりあえず、それはメインではないので説明は別の記事に譲ります。
<Validatorクラス>
まず、Validatorクラスを見てください。
errors.rejectValueという処理をしています。
これがメインの妥当性チェックの処理です。
errors.rejectValue("message", "error.required", "メッセージは必須です");
"message" ・・・ オブジェクトのプロパティ名(getter名)。
JSPファイルでエラーメッセージを出力するときにも指定します。
"error.required" ・・・ メッセージリソースからこの名称のメッセージを探してエラーメッセージにします。
引数がある場合は、3番目の引数にObject[]型で指定します。
"メッセージは必須です" ・・・ メッセージリソースから"error.required"が見つからないときにこの
メッセージを出力します。
このerrorsオブジェクトにはエラーとチェック対象オブジェクトを保持しています。
errorsオブジェクトが引き渡っていくことで最終的にはJSPに渡っていきます。
<errorsオブジェクトはどこからくるか?>
では、このerrorsオブジェクトはどこからValidatorに渡されるのでしょうか?
それは、Springの設定ファイルを見てみてください。
<bean id="validatorTestInputController" class="org.springframework.web.servlet.mvc.SimpleFormController">
<property name="commandClass" value="business.domain.CmdTest" />
<property name="formView" value="/WEB-INF/jsp/input.jsp" />
<property name="successView" value="/WEB-INF/jsp/input.jsp" />
<property name="validator" >
<bean class="validator.CmdTestValidator"/>
</property>
</bean>
SimpleFormControllerのプロパティとして設定されていますね。
はい。
そうです、SimpleformControllerがオブジェクトを作ってValidatorに渡してくるのです。
余談ですが、SimpleformControllerはBinderクラスというものを持っていて、
Binderがパラメタからオブジェクトを作っています。
Binderを変えることで独自のオブジェクトの作り方をさせることもできます。
これで画面表示の前までの処理はなんとなく分かったかと思います。
<JSPでの表示方法>
それでは、JSPでの表示方法を見てみましょう。
<form:errors path="*" cssStyle="font-weight: bold; color: red;"></form:errors>
簡単ですね。
Springで用意しているform:errors タグを使用するだけです。
ここでは pathを*にしていますが、errors.rejectValue()で指定した名称を指定できます!
例:
<form:errors path="message" cssStyle="font-weight: bold; color: red;">
エラー起きてますよ。
</form:errors>
中の「エラー起きてますよ。」は、エラーがおきているときだけ表示されます。
意外と便利でしょ?
他にも、spring:bindを使用する方法もありますが、formタグで十分でしょう。
興味があれば調べてみてください。
参考:
・SpringMVCを使用してWEBを作るには? (基礎編)