Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Struts2 資料驗證機制與表單標籤實戰

一、手動驗證

只要類別繼承 ActionSupport,直接覆寫 validate() 方法即可。它能對使用者的多個請求方法進行驗證,但邏輯是共用的:一旦 Action 覆寫了 validate(),預設每個請求方法執行時都會先經過它。

二、驗證檔的命名規則

使用 Struts2 驗證框架時,檔案名稱必須是 ActionName-validation.xml 或 ActionName-AliasName-validation.xml。前者是 Action 類別名,後者是 struts.xml 中 action 元素的 name 屬性值。

ActionName-validation.xml:驗證作用於整個 Action,適合只有單一處理方法、或多個方法共用同一套規則的情況。

ActionName-AliasName-validation.xml:更為靈活,只需對特定方法驗證時使用。

三、驗證檔的兩種風格

欄位驗證器(field validator)風格與非欄位驗證器風格,各有適用場景,前者直觀、後者更自由。

四、實戰一:表單標籤完成使用者註冊

(1)建立動態 Web 專案,加入 Struts2 相關套件,並在 web.xml 註冊 StrutsPrepareAndExecuteFilter:

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

(2)以 Struts2 表單標籤撰寫 index.jsp:

<%@ taglib uri="/struts-tags" prefix="s" %>
<h2>用戶註冊</h2>
<s:form action="userAction" method="post">
    <s:textfield name="name" label="用戶名" required="true" requiredposition="left"/>
    <s:password name="password" label="密碼" required="true" requiredposition="left"/>
    <s:radio name="sex" list="#{1:'男',0:'女'}" label="性別" required="true" requiredposition="left"/>
    <s:select list="{'請選擇省份','吉林','廣東','山東','河南'}" name="province" label="省份"/>
    <s:checkboxlist list="{'足球','羽毛球','乒乓球','籃球'}" name="hobby" label="愛好"/>
    <s:textarea name="description" cols="30" rows="5" label="描述"/>
    <s:submit value="註冊"/>
    <s:reset value="重置"/>
</s:form>

label 屬性定義標籤文字;required 會在元素邊緣顯示「*」,位置由 requiredposition 控制。

(3)success.jsp 以資料標籤輸出註冊資訊:

<ul>
    <li>用戶名:<s:property value="name"/></li>
    <li>密 碼:<s:property value="password"/></li>
    <li>性 別:<s:if test="sex==0">女</s:if><s:else>男</s:else></li>
    <li>省 份:<s:property value="province"/></li>
    <li>愛 好:<s:property value="hobby"/></li>
    <li>描 述:<s:property value="description"/></li>
</ul>

(4)UserAction 繼承 ActionSupport:

package com.cn.action;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction1 extends ActionSupport {
    private static final long serialVersionUID = 1L;
    private String name;        // 用戶名
    private String password;    // 密碼
    private String description; // 描述
    private int sex = 1;        // 性別
    private String province;    // 省份
    private String[] hobby;     // 愛好

    public String execute() throws Exception {
        return SUCCESS;
    }
    // getter / setter 略
}

(5)struts.xml 設定:

<struts>
    <constant name="struts.devMode" value="true"></constant>
    <constant name="struts.configuration.xml.reload" value="true"></constant>
    <package name="myPackage" extends="struts-default" namespace="/">
        <action name="userAction" class="com.cn.action.UserAction">
            <result>success.jsp</result>
        </action>
    </package>
</struts>

若註冊後頁面出現中文亂碼,把所有頁面的編碼統一設為 UTF-8 即可。

實戰二:用驗證框架做登入校驗

(1)UserAction 與 struts.xml 設定:

<action name="userAction" class="com.cn.action.UserAction">
    <result name="input">login.jsp</result>
    <result>success.jsp</result>
</action>

注意:驗證框架在失敗後預設返回 input 對應的結果,因此務必明確指定 input。

(2)login.jsp:

<s:form action="userAction" method="post">
    <s:textfield name="username" label="用戶名" required="true"/>
    <s:password name="password" label="密碼" required="true"/>
    <s:submit key="submit" value="登錄"/>
</s:form>

(3)驗證檔 UserAction-validation.xml,必須放在 UserAction 所在的套件中:

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN"
    "https://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>
    <field name="username">
        <field-validator type="requiredstring">
            <message>用戶名不能為空</message>
        </field-validator>
    </field>
    <field name="password">
        <field-validator type="requiredstring">
            <message>密碼不能為空</message>
        </field-validator>
        <field-validator type="stringlength">
            <param name="maxLength">10</param>
            <param name="minLength">5</param>
            <message>密碼長度應該在 ${minLength}--${maxLength} 位之間</message>
        </field-validator>
    </field>
</validators>

執行後,未填欄位或密碼長度不符時,頁面會停留在 login.jsp 並顯示對應的錯誤訊息;驗證通過則跳往 success.jsp。

Copyright © Linux教程網 All Rights Reserved