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

Struts2 資料校驗:為什麼要做,以及怎麼做

一、為什麼需要資料校驗

對 Web 應用而言,所有資料都來自瀏覽器,而使用者的輸入千奇百怪:操作不熟練、輸入錯誤、網路傳輸不穩,都可能產生異常輸入。

異常輸入輕則讓系統非預期中斷,重則直接崩潰。正確做法是遇到非法資料時給出明確提示,要求使用者輸入符合規格的內容,把這些異常資料過濾掉——這個過濾的過程,就是資料校驗。

二、如何實作

讓自訂類別繼承 com.opensymphony.xwork2.ActionSupport。這是 Struts2 預設的 Action 實作類,提供國際化、資料校驗與預設請求處理等方法。若 struts.xml 中省略 class 屬性,即代表存取 ActionSupport,其 execute() 直接回傳 SUCCESS。

login.jsp

<div>
    <!-- 輸出校驗訊息,fieldName 需與 addFieldError 的 key 對應 -->
    <s:fielderror fieldName="errorname"/>
    <s:fielderror fieldName="errorpwd"/>
</div>
<form action="Login.action" method="post">
    用戶名:<input type="text" name="username"/>
    密碼:<input type="text" name="userpwd"/>
    <input type="submit" value="登錄">
</form>

LoginAction

public class LoginAction extends ActionSupport {
    private String username;
    private String userpwd;

    @Override
    public void validate() {
        if (username.length() == 0) {
            // 添加欄位錯誤訊息
            addFieldError("errorname", "用戶名不能為空");
        }
        if (userpwd.length() == 0) {
            addFieldError("errorpwd", "密碼不能為空");
        }
    }

    @Override
    public String execute() throws Exception {
        if (username.equals("123") && userpwd.equals("123")) {
            // 以解耦方式取得 Session
            Map<String, Object> map = ActionContext.getContext().getSession();
            map.put("name", username);
            return SUCCESS;
        } else {
            return INPUT;
        }
    }
}

struts.xml

<struts>
    <!-- 開發模式:修改設定檔後無須重啟 Tomcat -->
    <constant name="struts.devMode" value="true"/>

    <package name="default" namespace="/" extends="struts-default">
        <action name="Login" class="cn.action.LoginAction">
            <result name="success">Login/success.jsp</result>
            <result name="input">Login/login.jsp</result>
        </action>
    </package>
</struts>

三、去掉框架自動產生的裝飾

Struts2 預設的 XHTML 主題會為表單元素加上表格與額外標籤,若不想要,可在 struts.xml 中切換主題:

<!-- 設定 UI 主題,預設為 XHTML -->
<constant name="struts.ui.theme" value="simple"></constant>

這也說明了 Struts2 的一貫風格:透過常數設定改變框架行為,而不必動到程式碼。

四、兩點實務提醒

validate() 中直接呼叫 username.length() 時,若參數完全未傳遞,username 會是 null 而拋出 NullPointerException。實務上應改用 username == null || username.trim().isEmpty() 這類寫法,或使用 requiredstring 驗證器交由框架處理。

另外,驗證失敗後返回 input 的前提是 struts.xml 已設定 <result name="input">,否則使用者只會看到一片空白。

Copyright © Linux教程網 All Rights Reserved