使用 Struts 驗證器

http://xiyuan.blogdriver.com/macrochen/406580.html

步驟 1. 安裝 Struts 應用程序

本節將指導您安裝一個現有的 Struts 應用程序。

導入 Struts 應用程序 EAR:

  1. 下載 StrutsValidator.zip 並解壓 DefaultEAR.ear
  2. 在工作區中,選擇 File => Import => EAR File。單擊 Next
  3. 找到下載的 EAR。
  4. 輸入 DefaultEAR 作爲項目名,然後單擊 Finish

在 WebSphere Test Environment 中運行 Struts 應用程序以確保安裝正確:

  1. 切換到 Web 透視圖。
  2. 展開 SimpleValidatorWeb => Web Content。右鍵單擊 submitpage.jsp 並選擇 Run on Server
  3. 確保 WebSphere Test Environment V5 Server 被選中。單擊 OK
  4. 在裝載完 submitpage.jsp 之後,隨便輸入點什麼,然後單擊 Submit 看看結果。
  5. 在測試完成之後,停止服務器。在 Web 透視圖的 Server 視圖中,右鍵單擊 WebSphere Test Environment V5 Server 並選擇 Stop

步驟 2. 使用 Struts 驗證器

驗證規則保存在一個名爲 validator-rules.xml 的 XML 文件中。Struts 提供了包含 14 個基本驗證器的 validator-rules.xml 文件。最常用的一些文件列舉如下:

驗證器名稱 功能
required 驗證一個必須填寫的字段是否填寫
mask 通過一個常規的 Jakarta RegExp 表達式檢查字段值。要了解更多關於 RegExp 的信息,請參見 Jakarta RegExp 頁。例如:
  ^[a-zA-Z]*$ 表示該值必須只包含字母
  ^\d{5}\d*$ 表示該值必須是五位數字
range 檢查該值是否在指定範圍內。
date 檢查該值是否爲一個有效值。它還能確保以期望的格式提供該數據,例如 MM/DD/YYYY 或 DD-MM-YYYY。
email 驗證該值是以有效的電子郵件地址的格式提供。
creditCard 確認該值是一個有效的信用卡號碼。

validator-rules.xml 導入 /Web Content/WEB-INF 文件夾。

  1. 下載 StrutsValidator.zip 並解壓 validator-rules.xml
  2. 在 Web Perspective 中,右鍵單擊 /SimpleValidatorWeb/Web Content/WEB-INF 並選擇 Import => File System
  3. 找到並選擇下載的 validator-rules.xml 文件。單擊 Finish
  4. 在文件夾 /SimpleValidatorWeb/Web Content/WEB-INF 中,雙擊 validator-rules.xml 以在 XML 編輯器中打開它。
  5. 切換到 Source 頁面。

validator-rules.xml 文件的代碼如下。驗證器規則必須封裝在標籤 <form-validation> 中。驗證器包含驗證邏輯。在以下示例中,驗證器爲 required,它包含客戶端和服務器端驗證的驗證代碼。用黃色顯示的代碼定義了服務器端驗證器類和方法,用綠色顯示的代碼定義了客戶端驗證的 JavaScript 代碼。該文件中的其餘驗證器採用了相同的結構。

<form-validation>
   <global>
      <validator name="required"

            classname="org.apache.struts.util.StrutsValidator"
               method="validateRequired"
         methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
                  msg="errors.required">

		<javascript><![CDATA[
		function validateRequired(form) {
		   var bValid = true;
		   var focusField = null;
		   var i = 0;
		   var fields = new Array();
		   oRequired = new required();
		   for (x in oRequired) {
		      if ((form[oRequired[x][0]].type == 'text' ||
 		           form[oRequired[x][0]].type == 'textarea' ||
 		           form[oRequired[x][0]].type == 'select-one' ||
 		           form[oRequired[x][0]].type == 'radio' ||
 		           form[oRequired[x][0]].type == 'password') &&
 		           (form[oRequired[x][0]].value == '')) {
 		               if (i == 0) {
 		                   focusField = form[oRequired[x][0]];
 		               }
 		               fields[i++] = oRequired[x][1];
		               bValid = false;
		       }
		   }
		   if (fields.length > 0) {
		        focusField.focus();
		        alert(fields.join('\n'));
		   }
		   return bValid;
		}]]> </javascript>

      </validator>

</global>
</form-validation>

如何使用這些驗證器?

在大部分情況下,內置的驗證器對於一個 Web 應用程序來說就足夠了。爲了在一個字段中使用驗證器,需要在一個 XML 文件中指定驗證器和字段之間的映射關係。在我們的示例中,它被命名爲 validation.xml

  1. 在 Web Perspective 中,右鍵單擊 /SimpleValidatorWeb/Web Content/WEB-INF 並選擇 New => Other => XML。單擊 Next 兩次。
  2. 輸入 validation.xml 作爲文件名。單擊 Finish
  3. 用以下代碼修改 XML 文件並保存。
   <form-validation>
      <formset>
         <form name="submitForm">
            <field property="name" depends="required">
               <arg0 key="submitForm.name" />
            </field>
         </form>
      </formset>
   </form-validation>

validation.xml 文件包含表單和每個字段依賴的驗證器之間的映射,submitForm 中的字段 name 依賴於 required 驗證器。arg0 是當錯誤消息產生時傳遞給驗證器的參數。參數的鍵在資源綁定文件中有一個映射。由於該字段是比需的,所以將會產生一個錯誤消息(如果這個字段爲空的話)。

將錯誤消息保存在哪兒?

將錯誤消息保存在 ApplicationResources.properties 中,它是由 WebSphere Studio 創建並由 Struts 框架使用的缺省資源綁定。

用編輯器打開特性文件:

  1. 在 Web Perspective 中,展開 SimpleValidatorWeb => Java™ source => com.ibm.simplevalidatorweb.resources,然後雙擊 ApplicationResources.properties
  2. 用以下黑體代碼修改該文件並保存。
# Optional header and footer for <errors/> tag.
#errors.header=<ul>
#errors.footer=</ul>

# Errors
errors.footer=
errors.header=<h3><font color="red">Validation Error</font></h3>
   You must correct the following error(s) before proceeding:
errors.ioException=I/O exception rendering error messages: {0}
error.database.missing=<li>User database is missing, cannot validate logon credentials</li>
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.

errors.byte={0} must be an byte.
errors.short={0} must be an short.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.float={0} must be an float.
errors.double={0} must be an double.

errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.

submitForm.name = text field label

在這個示例中,將會顯示錯誤消息 {0} is required,其中 {0} 由通過 <arg0 key="submitForm.name" />validation.xml 傳遞而來的參數替代。在這個示例中,submitForm.name 映射到(資源束文件resource bundle file)中的 text filed label,因此,最後的錯誤消息將會是 text field label is required

如果啓用了服務器端驗證,則錯誤消息將會在瀏覽器中作爲 HTML 返回。對於客戶端驗證,錯誤消息將會作爲 JavaScript 彈出窗口返回。

配置 Struts 配置文件以啓用驗證器插件

要啓用驗證器插件,請遵循下列步驟:

  1. 在編輯器中打開 struts-config.xml。展開 /SimpleValidatorWeb/Web Content/WEB-INF 並雙擊 struts-config.xml
  2. 切換到 Source 頁。
  3. 將以下代碼插到 </struts-config> 結束標籤前並保存修改。以下代碼可以啓用驗證器組件並且指示該插件使用 validator-rules.xmlvalidation.xml 來驗證動作表單:
    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
       <set-property property="pathnames" value="/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml"/>
    </plug-in>
    
  4. 切換到 struts-config.xml 編輯器的 Actions 頁,選擇 /submit 並在 Input 字段中輸入 /submitpage.jsp。保存修改。

下面的步驟 3 和 4 將指導您完成各個必需的過程以啓用服務器端驗證和客戶端驗證。

步驟 3. 使用服務器端驗證

爲了使用服務器端驗證,Action Form 實現類應該擴展 ValidatorForm 而不是 ActionForm。當提交表單時,會執行 ValidatorForm 中的 validate() 方法,它將根據 validation-rules.xmlvalidation.xml 文件進行驗證。

要在編輯器中打開 SubmitForm 類,請遵循下列步驟。

  1. 在 Web Perspective 中,雙擊 /SimpleValidatorWeb/Java Source/com.ibm.simplevalidatorweb.forms 內的 SubmitForm.java
  2. 如下所示修改 SubmitForm.java 並保存。
package com.ibm.simplevalidatorweb.forms;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.ValidatorForm;

/**
 * Form bean for a Struts application.
 * Users may access 1 field on this form:
 * <ul>
 * <li>name - [your comment here]
 * </ul>
 * @version 	1.0
 * @author
 */
public class SubmitForm extends ValidatorForm {

	private String name = null;

	/**
	 * Get name
	 * @return String
	 */
	public String getName() {
		return name;
	}

	/**
	 * Set name
	 * @param <code>String</code>
	 */
	public void setName(String n) {
		name = n;
	}
	/**
	* Constructor
	*/
	public SubmitForm() {

		super();

	}
	public void reset(ActionMapping mapping, HttpServletRequest request) {

		// Reset values are provided as samples only. Change as appropriate.

		name = null;

	}
	public ActionErrors validate(
		ActionMapping mapping,
		HttpServletRequest request) {
		return super.validate(mapping, request);
	}
}

您需要在 JSP 文件中添加 <html:errors/> 行以使錯誤顯示出來:

  1. 在編輯器中打開 submitpage.jsp 並切換到 Source 頁。
  2. 在文件的開頭(即 <html:form> 前)輸入行 <html:errors/>。保存該修改。

運行該應用程序

要在 WebSphere Test Environment 中運行 submitpage.jsp,請遵循下列步驟:

  1. 右鍵單擊 submitpage.jsp 並選擇 Run on Server
  2. 確保 WebSphere Test Environment V5 Server 被選中。單擊 OK

當在瀏覽器中裝載 submitpage.jsp 時,單擊 Submit,然後您將會接收到一個驗證錯誤,告知 text field label 是必需的。

圖 1. 運行 http://localhost:9080/SimpleValidatorWeb/submitpage.jsp

步驟 4. 使用客戶端驗證

爲了使用客戶端驗證,Action Form 應該擴展 ValidatorActionForm 而不是 ActionForm。如前所述,對於服務器端驗證,Action Form 擴展的是 ValidatorForm 類。

在編輯器中打開 SubmitForm 類。

  1. 在 Web 透視圖中,雙擊 /SimpleValidatorWeb/Java Source/com.ibm.simplevalidatorweb.forms 內的 SubmitForm.java
  2. 如下所示修改 SubmitForm.java 並保存。validate() 方法註釋掉了。要註釋一段代碼,可以選中該代碼塊,然後選擇 Source => Comment
package com.ibm.simplevalidatorweb.forms;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.ValidatorActionForm;
import org.apache.struts.validator.ValidatorForm;

/**
 * Form bean for a Struts application.
 * Users may access 1 field on this form:
 * <ul>
 * <li>name - [your comment here]
 * </ul>
 * @version 	1.0
 * @author
 */
public class SubmitForm extends ValidatorActionForm {

	private String name = null;

	/**
	 * Get name
	 * @return String
	 */
	public String getName() {
		return name;
	}

	/**
	 * Set name
	 * @param <code>String</code>
	 */
	public void setName(String n) {
		name = n;
	}
	/**
	* Constructor
	*/
	public SubmitForm() {

		super();

	}
	public void reset(ActionMapping mapping, HttpServletRequest request) {

		// Reset values are provided as samples only. Change as appropriate.

		name = null;

	}
//	public ActionErrors validate(
//		ActionMapping mapping,
//		HttpServletRequest request) {
//		return super.validate(mapping, request);
//	}
}

修改 submitpage.jsp 以啓用服務器端驗證:

  1. 在編輯器中打開 submitpage.jsp
  2. 如下所示修改該文件並保存。服務器端驗證時必需的行 <html:errors /> 在客戶端驗證時不再需要。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

<html:html>
<HEAD>

<%@ page
language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
%>

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM WebSphere Studio">

<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="theme/Master.css" rel="stylesheet"
	type="text/css">
<TITLE></TITLE>
</HEAD>

<BODY>

<html:form action="/submit" οnsubmit="return validateSubmitForm(this);">
<bean:message key="submitForm.name"/>: <html:text property="name"/>
<html:submit/>
</html:form>

</BODY>
<html:javascript formName="submitForm"/>
</html:html>

<html:javascript formName="submitForm"/> 中的 formName submitForm 必須與 validation.xmlstruts-config.xml 文件中的表單名稱相匹配。

運行該應用程序

由於我們對應用程序做了修改,所以我們必須重新啓動該 EAR 項目:

  1. 在 Server 視圖中,右鍵單擊 WebSphere V5 Test Environment 然後選擇 Restart Project => DefaultEAR
  2. 項目重新啓動後,右鍵單擊 submitpage.jsp 並選擇 Run on Server

submitpage.jsp 裝載到瀏覽器中後,單擊 Submit, 然後您將會看到一個彈出的 JavaScript 消息,告知字段 text field label 是必需的:

圖 2. 客戶端驗證中的 JavaScript 彈出窗口

步驟 5. 使用其他驗證器

有時,業務要求一個字段上有多個驗證器。Struts 驗證器使得一個字段可以由多個驗證器進行驗證。

例如,要添加一個電子郵件驗證器,可以如下編輯 validation.xml 並保存它:

<form-validation>
   <formset>
    <form name="submitForm">
    	<field property="name" depends="required,email">
    	<arg0 key="submitForm.name"/>
    	</field>
    </form>
   </formset>
</form-validation>

重新啓動 DefaultEAR 項目並再次運行 submitpage.jsp。輸入一個無效的電子郵件地址並提交,您將會接收到一個錯誤消息,告知它不是一個有效的電子郵件地址。另外,required 驗證器仍將繼續工作。

圖 3. e-mail 驗證器發出的錯誤消息

在某些情況下,您可能想提供一個更具體的錯誤消息而不是在資源束文件中定義的缺省錯誤消息。例如,如果您有一個 Mask 驗證器,缺省錯誤消息是,該值是無效的,而沒有關於無效性的詳細情況。您可以用另一個消息覆蓋 Mask 驗證器的錯誤消息,方式是將如下一行代碼添加到 validator.xml 中:<msg name="mask" key="some.other.error.msg"/>

將如下一行代碼添加到文件 ApplicationResources.properties 中並保存:

some.other.error.msg = {0} is not a 5-digit number

如下編輯 validation.xml 並保存:

<form-validation>
   <formset>
    <form name="submitForm">
    	<field property="name" depends="required,mask">
    	<msg name="mask" key="some.other.error.msg"/>
    	<arg0 key="submitForm.name"/>
         <var>
           <var-name>mask</var-name>
           <var-value>^\d{5}\d*$</var-value>
         </var>
    	</field>
    </form>
   </formset>
</form-validation>

重新啓動 DefaultEAR 項目並再次運行 submitpage.jsp。一個更具體的錯誤消息將會顯示出來。

圖 4. 一個自定義的錯誤消息

正在在使用的 Struts 驗證器

如前所述,隨 Struts 一起發佈大約有 14 種基本的 Struts 驗證器。每個驗證器都可能要求不同的參數,而您必須提供正確的參數以使用它們。在本節中,您將在一個更爲複雜的 Struts 應用程序中看到更多正在使用的驗證器。

StrutsValidation.war 文件導入 DefaultEAR

  1. 下載 StrutsValidator.zip 並解壓 StrutsValidation.war
  2. 在工作區中,選擇 File => Import => WAR file。單擊 Next
  3. 找到下載的 WAR 文件。
  4. 確保 New Web 項目被選中。輸入 StrutsValidationWeb 作爲該 Web 項目名。
  5. 確保 Existing 企業應用程序被選中。找到 DefaultEAR
  6. 單擊 Finish
  7. 如果出現一個對話框,通知您該 Web 項目將添加到服務器中,則單擊 OK

重新啓動服務器並在 StrutsValidationWeb 中運行 submitpage.jsp

  1. 在 Web 透視圖——Server 視圖中,右鍵單擊 WebSphere V5 Test Environment 並選擇 Restart
  2. 展開 StrutsValidationWeb => Web Content,右鍵單擊 submitpage.jsp 並選擇 Run on Server
  3. 在該 JSP 頁面裝載完畢之後,單擊 Submit,您將會接收到這些錯誤消息:

圖 5. 正在使用的 Struts 驗證器

讓我們來分析一下 validation.xml。在編輯器中打開 validation.xml。它在 /StrutsValidationWeb/Web Content/WEB-INF 中。

<form-validation>
   <global>
      <constant>
        <constant-name>phone</constant-name>
        <constant-value>^\(?(\d{3})\)?[-| ]?(\d{3})[-| ]?(\d{4})$</constant-value>
      </constant>
      <constant>
        <constant-name>zip</constant-name>
        <constant-value>^\d{5}\d*$</constant-value>
      </constant>
   </global>
   <formset>
      <constant>
        <constant-name>zip</constant-name>
        <constant-value>^\d{5}(-\d{4})?$</constant-value>
      </constant>

      <form    name="submitForm">
         <field    property="customer.firstName"
         	   depends="required,mask,minlength">
         	     <arg0 key="submitForm.customer.firstname"/>
         	     <arg1 name="minlength" key="${var:minlength}" resource="false"/>
                     <var>
                       <var-name>mask</var-name>
                       <var-value>^\w+$</var-value>
                     </var>
                     <var>
                       <var-name>minlength</var-name>
                       <var-value>5</var-value>
                     </var>
         </field>
         <field    property="customer.lastName"
         	   depends="required,mask,maxlength">
         	     <msg name="mask" key="submitForm.lastname.maskmsg"/>
         	     <arg0 key="submitForm.customer.lastname"/>
         	     <arg1 name="maxlength" key="${var:maxlength}" resource="false"/>
                     <var>
                       <var-name>mask</var-name>
                       <var-value>^[a-zA-Z]*$</var-value>
                     </var>
                     <var>
                       <var-name>maxlength</var-name>
                       <var-value>10</var-value>
                     </var>
         </field>
         <field    property="customer.address"
         	   depends="required">
         	     <arg0 key="submitForm.customer.address"/>
         </field>
         <field    property="customer.city"
         	   depends="required,mask">
         	     <arg0 key="submitForm.customer.city"/>
                     <var>
                       <var-name>mask</var-name>
                       <var-value>^[a-zA-Z]*$</var-value>
                     </var>
         </field>
         <field    property="customer.state"
         	   depends="required,mask">
         	     <arg0 key="submitForm.customer.state"/>
                     <var>
                       <var-name>mask</var-name>
                       <var-value>^[a-zA-Z]*$</var-value>
                     </var>
         </field>
         <field    property="customer.zip"
         	   depends="required,mask">
         	     <arg0 key="submitForm.customer.zip"/>
                     <var>
                       <var-name>mask</var-name>
                       <var-value>${zip}</var-value>
                     </var>
         </field>
         <field    property="customer.phone"
         	   depends="mask">
         	     <arg0 key="s
         	     ubmitForm.customer.phone"/>
                     <var>
                       <var-name>mask</var-name>
                       <var-value>${phone}</var-value>
                     </var>
         </field>
         <field    property="customer.email"
         	   depends="required,email">
         	     <arg0 key="submitForm.customer.email"/>
         </field>

         <field    property="creditcard.date"
         	   depends="required,date">
         	     <arg0 key="submitForm.creditcard.date"/>
                     <var>
                       <var-name>datePatternStrict</var-name>
                       <var-value>MM-dd-yyyy</var-value>
                     </var>
         </field>
         <field    property="creditcard.number"
         	   depends="required,creditCard">
         	     <arg0 key="submitForm.creditcard.number"/>
         </field>

      </form>
   </formset>
</form-validation>

下面是 Last Name 字段的代碼。它依賴於 3 個驗證器:required、maskmaxlengthrequired 驗證器,如前所述,確保填寫了該字段。mask 驗證器在這個示例中檢查是否所有的值都是字母。mask 驗證器的 RegExp 表達式檢查字母是否是 ^[a-zA-Z]*$maxlength 驗證器確保這個示例中的字段的長度小於或等於 10。

示例 1. Last Name 字段的驗證器映射

<field property="customer.lastName"
   depends="required,mask,maxlength">
      <msg name="mask" key="submitForm.lastname.maskmsg"/>
      <arg0 key="submitForm.customer.lastname"/>
      <arg1 name="maxlength" key="${var:maxlength}" resource="false"/>
      <var>
         <var-name>mask</var-name>
         <var-value>^[a-zA-Z]*$</var-value>
      </var>
      <var>
         <var-name>maxlength</var-name>
         <var-value>10</var-value>
      </var>
</field>

下面的示例是使用 mask 驗證器的一個小小的變種。這段代碼是爲 Phone 字段而寫的。mask 驗證器包含參數 ${phone},它是在 validation.xml 文件的開頭定義的一個常量(請參見示例 3)。

示例 2. Phone 字段的驗證器映射

<field property="customer.phone"
   depends="mask">
      <arg0 key="submitForm.customer.phone"/>
      <var>
         <var-name>mask</var-name>
         <var-value>${phone}</var-value>
      </var>
</field>

示例 3. phone 常量

<constant>
   <constant-name>phone</constant-name>
   <constant-value>^\(?(\d{3})\)?[-| ]?(\d{3})[-| ]?(\d{4})$</constant-value>
</constant>

下面的代碼是爲 Date 字段而寫的。您可以在 date 驗證器上使用它本身,如示例 4 所示——它根據地區驗證日期的格式。您也可以指定一個日期模式,如示例 5 所示:

示例 4. Date 驗證器

<field property="creditcard.date"
   depends="required,date">
   	  <arg0 key="submitForm.creditcard.date"/>
</field>

示例 5. 帶 datePatternStrict 的 Date 驗證器

<field property="creditcard.date"
   depends="required,date">
   	  <arg0 key="submitForm.creditcard.date"/>
      <var>
         <var-name>datePatternStrict</var-name>
         <var-value>MM-dd-yyyy</var-value>
      </var>
</field>

這個示例也適用於 emailcreditCard 驗證器。由於這兩個驗證器都很簡單,所以您可以自己去分析它們。

結束語

Struts 驗證器框架使您能夠使用服務器端和客戶端驗證。您可以在大多數 Web 應用程序中不加修改地使用內置的規則集。出於性能方面的考慮,客戶端驗證通常是更好的選擇。

Struts 框架通過應用模型-視圖-控制器(Model-View-Controller)範式解耦 Web 組件。Struts Tiles 框架將頁面佈局與表示層分離開來,而 Struts 驗證器框架將驗證邏輯和業務邏輯分離開來。使用 Struts 與 Struts 的相關框架可以使您的 Web 應用程序具有更好的可維護性和可重用性。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章