クライアント側妥当性検査の実装: デザインの詳細

このサンプルアプリケーションは、JavaServer[tm] Faces テクノロジを使用したクライアント側妥当性検査の例です。 このアプリケーションは、java.net 主催の bpcatalog プロジェクトにあります。

このアプリケーションは、index.jsp および response.jsp ファイルの 2 つの JavaServer Faces ページで構成されています。このうち index.jsp ページには、1 つのページにすべての JavaServer Faces コード例が含まれています。ページ内のデータが有効である場合は、response.jsp ページに要求が送信され、妥当性検査で問題が起きた場合は、index.jsp に戻ってエラーメッセージが表示されます。

このデザインドキュメントでは、このアプリケーションを構成するページとソースファイル、構成ファイルの一部について説明します。

ColorRenderer

カスタムレンダリングの ColorRenderer は、その encodeEnd メソッドから client_validation JavaScript[tm] 機能を index.jsp ファイルに描画します。以下は、その encodeEnd メソッドからの抜粋です。

    public void encodeEnd(FacesContext context, UIComponent component)
        throws IOException {

        if ((context == null) || (component == null)) {
            throw new NullPointerException();
        }

        UIOutput script = (UIOutput) component;
        UIInput currentColor = (UIInput) component.findComponent("color");
        ResponseWriter writer = context.getResponseWriter();

        StringBuffer sb = null;
        System.out.println("currentColor =" + currentColor);
        if (currentColor == null) return;
        sb = new StringBuffer("function client_validation() {\n");
        sb.append("if (document.forms[0]['");
        sb.append(currentColor.getClientId(context));
        sb.append("'].value=='red' ) {").append("\n");
        sb.append("return true;");
        sb.append("\n} else if (document.forms[0]['");
        sb.append(currentColor.getClientId(context));
        sb.append("'].value=='green' ) {").append("\n");
        sb.append("return true;");
        sb.append("\n} else if (document.forms[0]['");
        sb.append(currentColor.getClientId(context));
        sb.append("'].value=='blue' ) {").append("\n");
        sb.append("return true;");
        sb.append("\n } else {\n");
        sb.append("alert('Enter red, green, or blue for the color.');");
        sb.append("\nreturn false;\n");
        sb.append("} \n }");
        sb.append("\n");
...

ScriptTag

新しいコンポーネント/レンダリングの組み合わせを作成した場合は、その組み合わせをページ上で表すためのカスタムタグを作成する必要もあります。 このカスタムタグは script という名前です。この script タグは、JSP[tm] (JavaServer Page[tm]) ページを HTML に変換するときに、クライアント側妥当性検査を行う JavaScript に変換されます。 ScriptTag クラスは、ColorRenderer によって描画された JavaScript を表示する、カスタム script タグのタグハンドラです。

ColorValidator

次に示すように、このクラスはサーバー側妥当性検査を行います。

 public void validate(FacesContext context, UIComponent component, Object toValidate) {
String value = null;
if ((context == null) || (component == null)) {
throw new NullPointerException();
}
if (!(component instanceof UIInput)) {
return;
}
if ( null == toValidate) {
return;
}

value = toValidate.toString();

if (value.equals("red") || value.equals("green") || value.equals("blue")) {
return;
} else {
System.out.println("value "+value);
FacesMessage errMsg = MessageFactory.getMessage(context,
COLOR_INVALID_MESSAGE_ID);
throw new ValidatorException(errMsg);
}
}

customTags.tld

カスタム script タグを作成するには、そのタグハンドラクラスを作成し、TLD ファイルにそのタグを定義する必要があります。 ScriptTag は、この script タグのタグハンドラです。 スクリプトタグは、script.tld ファイルで定義します。この TLD は JavaScript を表示するカスタム script タグの定義で、 以下のようになっています。

<tag>
<name>script</name>
<tag-class>com.sun.j2ee.blueprints.catalog.validator.ScriptTag</tag-class>
<body-content>empty</body-content>
...
<attribute>
<name>language</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<type>String</type>
</attribute>
</tag>

faces-config.xml

アプリケーションでカスタムレンダリングと妥当性検査を使用するには、この構成ファイルにそれらを登録する必要があります。 構成ファイル内の、カスタムレンダリングと妥当性検査の登録する要素は、次のようになっています。

  <render-kit>
    ...
    <renderer>
...
      <component-family>javax.faces.Output</component-family>
      <renderer-type>Color</renderer-type>
      <renderer-class>com.sun.j2ee.blueprints.catalog.validator.ColorRenderer
</renderer-class>
    </renderer>
</render-kit>

 <validator>
...
<validator-id>ColorValidator</validator-id>
<validator-class>com.sun.j2ee.blueprints.catalog.validator.ColorValidator
</validator-class>
<attribute>
<attribute-name>color</attribute-name>
<attribute-class>java.lang.String</attribute-class>
</attribute>
</validator>


index.jsp

このページには、妥当性検査されるデータの入力コンポーネントが含まれています。 このページは、入力コンポーネントにサーバー側妥当性検査 ColorValidator を登録し、このコンポーネントのデータのクライアント側妥当性検査を行う JavaScript を表示します。

次は、カスタムサーバー側妥当性検査が登録された入力コンポーネントです。
<h:inputText id="color" >
          <f:validator validatorId="ColorValidator" />
</h:inputText>

次は、ページが HTML に変換されたときにカスタムレンダリング ColorRenderer によって描画された JavaScript を表示するカスタムスクリプトタグです。

<customTags:script/>

このスクリプトタグを使用するには、JSP ページからそのタグを参照する taglib 指示がこのページに含まれる必要があります。

<%@ taglib prefix="customTags" uri="WEB-INF/customTags.tld" %>

フォームタグの onsubmit 属性は、client_validation JavaScript メソッドを呼び出します。

<h:form id="validatorForm" onsubmit="return client_validation();" />

© Sun Microsystems 2004. All of the material in The Java BluePrints Solutions Catalog is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.