struts可以繼承ActionSupport類,也可以不繼承,繼承的好處簡單來說就是更方便實現(xiàn)驗證,國際化等功能,與struts2的功能結(jié)合緊密,方便我們開發(fā)。
ActionSupport類的作用:
此類實現(xiàn)了很多實用的接口,提供了很多默認的方法,這些默認方法包括國際化信息,默認的處理用戶請求的方法等,可以大大簡化action的開發(fā),在繼承ActionSupport的情況下,必須有無參構(gòu)造函數(shù)。
下面用在struts2框架搭建完成的基礎(chǔ)上,用 用戶請求的例子來實現(xiàn)ActionSupport類:
1.創(chuàng)建視圖層兩個頁面index.jsp和welcome.jsp頁面,下面只展示index.jsp頁面,welcome.jsp頁面的代碼自己簡單寫一下看一下效果就行。這個jsp頁面的<s:fielderror/>標簽會在相應(yīng)的字段處輸出錯誤信息。
<%@ page language="java" contentType="text/html; charset=utf-8" <%@ taglib prefix="s" uri="/struts-tags"%> <meta http-equiv="Content-Type" content="text/html; utf-8"> <title>Insert title here</title> <form action="helloworldAction" method="post"> <input type="hidden" name="submitFlag" value="login"/> <font color=red><s:fielderror fieldName="account"/></font> 賬號:<input type="text" name="account"> <font color=red><s:fielderror fieldName="password"/></font> 密碼:<input type="password" name="password"> <input type="submit" value="提交">
2.實現(xiàn)action類封裝HTTP請求參數(shù),類里面應(yīng)該包含與請求參數(shù)對應(yīng)的屬性,并為屬性提供get,set方法,再說一次,在繼承ActionSupport的情況下,必須有無參構(gòu)造函數(shù)。
validate方法內(nèi)部,對請求傳遞過來的數(shù)據(jù)進行校驗,而且我們也能看出來同一個數(shù)據(jù)可以進行多方面的驗證,如果不滿足要求,內(nèi)容將會在頁面上直接顯示。里面重寫了 execute() throws Exception方法,返回字符串。
import com.opensymphony.xwork2.ActionSupport; public class RegisterAction extends ActionSupport{ private String submitFlag; public String execute() throws Exception { if(account==null || account.trim().length()==0){ this.addFieldError("account", "賬號不可以為空"); if(password==null || password.trim().length()==0){ this.addFieldError("password", "密碼不可以為空"); if(password!=null && !"".equals(password.trim()) && password.trim().length()<6){ this.addFieldError("password", "密碼長度至少為6位"); public void businessExecute(){ System.out.println("用戶輸入的參數(shù)為==="+"account="+account+",password="+password+",submitFlag="+submitFlag); public String getAccount() { public void setAccount(String account) { public String getPassword() { public void setPassword(String password) { this.password = password; public String getSubmitFlag() { public void setSubmitFlag(String submitFlag) { this.submitFlag = submitFlag;
3.從上面我們也可以看出來,validate方法是沒有返回值的,如果驗證不成功的話,錯誤信息該怎么在頁面上顯示出來呢?我們需要在struts.xml中的Action配置里面,添加一個名稱為input的result配置,沒有通過驗證,那么會自動跳轉(zhuǎn)回到該action中名稱為input的result所配置的頁面。
<?xml version="1.0" encoding="UTF-8"?> "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts./dtds/struts-2.0.dtd"> <package name="helloworld" extends="struts-default"> <action name="helloworldAction" class="com.hnpi.action.RegisterAction"> <result name="toWelcome">/welcome.jsp</result> <result name="input">/index.jsp</result>
下面我們來看一下代碼效果圖:

這個例子可以看出來,validate方法會先于execute方法被執(zhí)行,只有validate方法執(zhí)行后,又沒有發(fā)現(xiàn)驗證錯誤的時候,才會運行execute方法,否則會自動跳轉(zhuǎn)到你所配置的input所對應(yīng)的頁面。
|