Struts2 XML配置詳解
1、深入Struts2的配置檔案
本部分主要介紹struts.xml的常用配置。1.1. 包配置:
Struts2框架中核心元件就是Action、攔截器等,Struts2框架使用包來管理Action和攔截器等。每個包就是多個Action、多個攔截器、多個攔截器引用的集合。 在struts.xml檔案中package元素用於定義包配置,每個package元素定義了一個包配置。它的常用屬性有: 1、name:必填屬性,用來指定包的名字。 2、extends:可選屬性,用來指定該包繼承其他包。繼承其它包,可以繼承其它包中的Action定義、攔截器定義等。 3、namespace:可選屬性,用來指定該包的名稱空間。<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- struts2的action必須放在一個指定的包空間下定義 --> <package name="default" extends="struts-default"> <!-- 定義處理請求URL為login.action的Action --> <action name="login" class="org.qiujy.web.struts.action.LoginAction"> <!-- 定義處理結果字串和資源之間的對映關係 --> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts>
如上示例的配置,配置了一個名為default的包,該包下定義了一個Action。
1.2. 名稱空間配置:
考慮到同一個Web應用中需要同名的Action,Struts2以名稱空間的方式來管理Action,同一個名稱空間不能有同名的Action。Struts2通過為包指定namespace屬性來為包下面的所有Action指定共同的名稱空間。 把上示例的配置改為如下形式:<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- struts2的action必須放在一個指定的包空間下定義 --> <package name="qiujy" extends="struts-default"> <!-- 定義處理請求URL為login.action的Action --> <action name="login" class="org.qiujy.web.struts2.action.LoginAction"> <!-- 定義處理結果字串和資源之間的對映關係 --> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package> <package name="my" extends="struts-default" namespace="/manage"> <!-- 定義處理請求URL為login.action的Action --> <action name="backLogin" class="org.qiujy.web.struts2.action.LoginAction"> <!-- 定義處理結果字串和資源之間的對映關係 --> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package></struts>
如上配置了兩個包:default和my,配置my包時指定了該包的名稱空間為/manage。
對於包default:沒有指定namespace屬性。如果某個包沒有指定namespace屬性,即該包使用預設的名稱空間,預設的名稱空間總是""。 對於包my:指定了名稱空間/manage,則該包下所有的Action處理的URL應該是“名稱空間/Action名”。如上名為backLogin的Action,它處理的URL為:http://localhost:8080/userlogin_struts2/manage/backLogin.action Struts2的名稱空間的作用等同於struts1裡模組的作用。1.3. 包含配置:
在Struts2中可以將一個配置檔案分解成多個配置檔案,那麼我們必須在struts.xml中包含其他配置檔案。<struts>
<include file="struts-default.xml"/>
<include file="struts-user.xml"/>
<include file="struts-book.xml"/>
<include file="struts-shoppingCart.xml"/>
......
</struts>
1.4. 攔截器配置:
見後面章節介紹。1.5. 常量配置:
Struts2框架有兩個核心配置檔案,其中struts.xml檔案主要負責管理應用中的Action對映, 及Action處理結果和物理資源之間的對映關係。除此之外,Struts2框架還包含了一個struts.properties檔案,該檔案主義了Struts2框架的大量常量屬性。但通常推薦也是在struts.xml檔案中來配置這些常量屬性。 如:後面會講到Struts2的國際化,它的資原始檔位置就用常量屬性來指定:<struts>
......
<constant name="struts.custom.i18n.resources" value="messages"/>
</struts>
表示指定了資原始檔的放置在classes目錄下,基本名是messages,則在classes目錄下您就應該放置類似messages_zh_CN.properties,message_en.properties名的檔案。
2、 Struts2的Action
2.1. 實現Action類:
Struts2中Action是核心內容,它包含了對使用者請求的處理邏輯,我們也稱Action為業務控制器。 Struts2中的Action採用了低侵入式的設計,Struts2不要求Action類繼承任何的Struts2的基類或實現Struts2介面。(但是,我們為了方便實現Action,大多數情況下都會繼承com.opensymphony.xwork2.ActionSupport類,並重寫此類裡的public String execute() throws Exception方法。因為此類中實現了很多的實用介面,提供了很多預設方法,這些預設方法包括獲取國際化資訊的方法、資料校驗的方法、預設的處理使用者請求的方法等,這樣可以大大的簡化Action的開發。) Struts2中通常直接使用Action來封裝HTTP請求引數,因此,Action類裡還應該包含與請求引數對應的屬性,並且為屬性提供對應的getter和setter方法。(當然,Action類中還可以封裝處理結果,把處理結果資訊當作一屬性,提供對應的getter和setter方法) 修改第一部分的使用者登入示例:把Action改成如下:package org.qiujy.web.struts2.action; import com.opensymphony.xwork2.ActionSupport; /** *@authorqiujy *@version1.0 */ publicclass LoginAction extends ActionSupport{ private String userName; private String password; private String msg; //結果資訊屬性 /** *@returnthemsg */ public String getMsg() { returnmsg; } /** *@parammsgthemsgtoset */ publicvoid setMsg(String msg) { this.msg = msg; } /** *@returntheuserName */ public String getUserName() { returnuserName; } /** *@paramuserNametheuserNametoset */ publicvoid setUserName(String userName) { this.userName = userName; } /** *@returnthepassword */ public String getPassword() { returnpassword; } /** *@parampasswordthepasswordtoset */ publicvoid setPassword(String password) { this.password = password; } /** *處理使用者請求的excute()方法 *@return結果導航字串 *@throwsException */ public String execute() throws Exception{ if("test".equals(this.userName) && "test".equals(this.password)){ msg = "登入成功,歡迎" + this.userName; returnthis.SUCCESS; }else{ msg = "登入失敗,使用者名稱或密碼錯"; returnthis.ERROR; } } }
往success.jsp和error.jsp頁面中新增 ${msg}EL表示式來顯示結果資訊。則最終效果跟以前一樣。
2.2. Action訪問Servlet API:
Struts2中的Action並沒有和任何Servlet API耦合,這樣框架更具靈活性,更易測試。但是,對於web應用的控制器而言,不訪問Servlet API幾乎是不可能的,例如跟蹤HTTP Session狀態等。Struts2框架提供了一種更輕鬆的方式來訪問Servlet API。Struts2中提供了一個ActionContext類(當前Action的上下文物件),通過這個類可以訪問Servlet API。下面是該類中提供的幾個常用方法: 1、public static ActionContext getContext() :獲得當前Action的ActionContext例項。 2、public Object get(Object key) :此方法類似於呼叫HttpServletRequest的getAttribute(String name)方法。 3、public void put(Object key, Object value) :此方法類似於呼叫HttpServletRequest 的setAttribute(String name, Object o)。 4、public Map getParameters() :獲取所有的請求引數。類似於呼叫HttpServletRequest物件的getParameterMap() 方法。 5、public Map getSession() :返回一個Map物件,該Map物件模擬了HttpSession例項。 6、public void setSession(Map session) : 直接傳入一個Map例項,將該Map例項裡的key-value對轉換成session的屬性名-屬性值對。 7、public Map getApplication() :返回一個Map物件,該物件模擬了該應用的ServletContext例項。 8、public void setApplication(Map application) :直接傳入一個Map例項,將該Map例項裡的key-value對轉換成application的屬性名-屬性值對。 修改以上使用者登入驗證示例的Action類中的execute方法:public String execute() throws Exception{ if("test".equals(this.userName) && "test".equals(this.password)){ msg = "登入成功,歡迎" + this.userName; //獲取ActionContext例項,通過它來訪問Servlet API ActionContext context = ActionContext.getContext(); //看session中是否已經存放了使用者名稱,如果存放了:說明已經登入了; //否則說明是第一次登入成功 if(null != context.getSession().get("uName")){ msg = this.userName + ":你已經登入過了!!!"; }else{ context.getSession().put("uName", this.userName); } returnthis.SUCCESS; }else{ msg = "登入失敗,使用者名稱或密碼錯"; returnthis.ERROR; } }
Struts2中通過ActionContext來訪問Servlet API,讓Action徹底從Servlet API 中分離出來,最大的好處就是可以脫離Web容器測試Action。另外,Struts2中還提供了一個ServletActionContext類,Action只要繼承自該類,就可以直接訪問Servlet API。具體方法參看struts2的API文件。
3、一個Action內包含多個請求處理方法的處理
Struts1提供了DispatchAction,從而允許一個Action內包含多個請求處理方法。Struts2也提供了類似的功能。處理方式主要有以下三種方式:3.1. 動態方法呼叫:
DMI:Dynamic Method Invocation 動態方法呼叫。 動態方法呼叫是指:表單元素的action不直接等於某個Action的名字,而是以如下形式來指定對應的動作名:<form method="post" action="userOpt!login.action">
則使用者的請求將提交到名為”userOpt”的Action例項,Action例項將呼叫名為”login”方法來處理請求。同時login方法的簽名也是跟execute()一樣,即為public String login() throws Exception。
注意:要使用動態方法呼叫,必須設定Struts2允許動態方法呼叫,通過設定struts.enable.DynamicMethodInvocation常量來完成,該常量屬性的預設值是true。3.1.1. 示例:
修改使用者登入驗證示例,多增加一個註冊使用者功能。 1、修改Action類:package org.qiujy.web.struts2.action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; /** *@authorqiujy *@version1.0 */ publicclass LoginAction extends ActionSupport{ private String userName; private String password; private String msg; //結果資訊屬性 /** *@returnthemsg */ public String getMsg() { returnmsg; } /** *@parammsgthemsgtoset */ publicvoid setMsg(String msg) { this.msg = msg; } /** *@returntheuserName */ public String getUserName() { returnuserName; } /** *@paramuserNametheuserNametoset */ publicvoid setUserName(String userName) { this.userName = userName; } /** *@returnthepassword */ public String getPassword() { returnpassword; } /** *@parampasswordthepasswordtoset */ publicvoid setPassword(String password) { this.password = password; } /** *處理使用者請求的login()方法 *@return結果導航字串 *@throwsException */ public String login() throws Exception{ if("test".equals(this.userName) && "test".equals(this.password)){ msg = "登入成功,歡迎" + this.userName; //獲取ActionContext例項,通過它來訪問Servlet API ActionContext context = ActionContext.getContext(); //看session中是否已經存放了使用者名稱,如果存放了:說明已經登入了; //否則說明是第一次登入成功 if(null != context.getSession().get("uName")){ msg = this.userName + ":你已經登入過了!!!"; }else{ context.getSession().put("uName", this.userName); } returnthis.SUCCESS; }else{ msg = "登入失敗,使用者名稱或密碼錯"; returnthis.ERROR; } } public String regist() throws Exception{ //將使用者名稱,密碼新增到資料庫中 //... msg = "註冊成功。"; returnthis.SUCCESS; } }
2、struts.xml檔案:沒有什麼變化,跟以前一樣配置
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="my" extends="struts-default" namespace="/manage"> <!-- 定義處理請求URL為login.action的Action --> <action name="userOpt" class="org.qiujy.web.struts2.action.LoginAction"> <!-- 定義處理結果字串和資源之間的對映關係 --> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts>
3、頁面:
index.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <html> <head> <title>使用者登入頁面</title> </head> <body> <h2>使用者入口</h2> <hr> <form action="manage/userOpt!login.action" method="post"> <table border="1"> <tr> <td>使用者名稱:</td> <td><input type="text" name="userName"/></td> </tr> <tr> <td>密碼:</td> <td><input type="password" name="password"/></td> </tr> <tr> <td colspan="2"> <input type="submit" value=" 確定 "/> </td> </tr> </table> </form> </body> </html>
regist.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <html> <head> <title>使用者註冊頁面</title> </head> <body> <h2>使用者註冊</h2> <hr> <form action="manage/userOpt!regist.action" method="post"> <table border="1"> <tr> <td>使用者名稱:</td> <td><input type="text" name="userName"/></td> </tr> <tr> <td>密碼:</td> <td><input type="password" name="password"/></td> </tr> <tr> <td colspan="2"> <input type="submit" value=" 註冊 "/> </td> </tr> </table> </form> </body> </html>
3.2. 為Action配置method屬性:
將Action類中的每一個處理方法都定義成一個邏輯Action方法。<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="my" extends="struts-default" namespace="/manage"> <action name="userLogin" class="org.qiujy.web.struts2.action.LoginAction" method="login"> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> <action name="userRegist" class="org.qiujy.web.struts2.action.LoginAction"method="regist"> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts>
如上,把LoginAction中的login和regist方法都配置成邏輯Action。要呼叫login方法,則相應的把index.jsp中表單元素的action設定為"manage/userLogin.action";要呼叫regist方法,把regist.jsp中表單元素的action設定為"manage/userRegist.action"。
3.3. 使用萬用字元對映(wildcard mappings)方式:
在struts.xml檔案中配置<action…>元素時,它的name、class、method屬性都可支援萬用字元,這種萬用字元的方式是另一種形式的動態方法呼叫。當我們使用萬用字元定義Action的name屬性時,相當於用一個元素action定義了多個邏輯Action:<action name="user_*"
class="org.qiujy.web.struts2.action.UserAction" method="{1}">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
如上,<action name=”user_*”>定義一系列請求URL是user_*.action模式的邏輯Action。同時method屬性值為一個表示式{1},表示它的值是name屬性值中第一個*的值。例如:使用者請求URL為user_login.action時,將呼叫到UserAction類的login方法;使用者請求URL為user_regist.action時,將呼叫到UserAction類的regist方法。
4、處理結果
Struts2的Action處理完使用者請求後,將返回一個普通字串,整個普通字串就是一個邏輯檢視名。Struts2通過配置邏輯檢視名和物理檢視資源之間的對映關係,一旦系統收到Action返回的某個邏輯檢視名,系統就會把對應的物理檢視資源呈現給瀏覽者。4.1. 配置處理結果:
Struts2的Action處理使用者請求結束後,返回一個普通字串-邏輯檢視名,必須在struts.xml檔案中完成邏輯檢視和物理檢視資源的對映,才可讓系統轉到實際的檢視資源。 Struts2通過在struts.xml檔案中使用<result …/>元素來配置結果。Struts2提供了兩種結果: 1、區域性結果:將<result …/>作為<action …>元素的子元素配置。 2、全域性結果:將<result …/>作為<global-results …>元素的子元素配置。 在package元素中配置<global-results>子元素:<global-results> <result name="error">/Error.jsp</result> <result name="invalid.token">/Error.jsp</result> <result name="login" type="redirect-action">Logon!input</result> </global-results>
4.2. 處理結果型別:
Struts2提供了對不同種類返回結果的支援,常見的有JSP,FreeMarker,Velocity等。Struts2支援的不同型別的返回結果為:名字 | 說明 |
chain | 用來處理Action鏈 |
dispatcher | 用來轉向頁面,通常處理JSP,這是預設的結果型別 |
freeMarker | 處理FreeMarker模板 |
httpHeader | 用來控制特殊的Http行為 |
redirect | 重定向到一個URL |
redirect-action | 重定向到一個Action |
stream | 向瀏覽器傳送InputSream物件,通常用來處理檔案下載 |
velocity | 處理Velocity模板 |
xslt | 處理XML/XLST模板 |
plaintext | 顯示原始檔案內容,例如檔案原始碼 |
tiles | 結合Tile使用 |
另外第三方的Result型別還包括JasperReports Plugin,專門用來處理JasperReport型別的報表輸出;Jfreechart Plugin;JSF Plugin。
4.3.動態返回結果
有些時候,只有當Action執行完畢的時候我們才知道要返回哪個結果,這個時候我們可以在Action內部定義一個屬性,這個屬性用來儲存Action執行完畢之後的result值,例如:private String nextAction; public String getNextAction() { return nextAction; }
在strutx.xml配置檔案中,我們可以使用${nextAction}來引用到Action中的屬性,通過${nextAction}表示的內容來動態的返回結果,例如:
<action name="fragment" class="FragmentAction">
<result name="next" type="redirect-action">${nextAction}</result>
</action>
上述Action的execute方法返回next的時候,還需要根據nextAction的屬性來判斷具體定位到哪個Action。
5、屬性驅動和模型驅動
不管屬性驅動還是模型驅動,Struts2框架都是通過攔截器負責提取請求引數,並將請求資料封裝到相應的Action例項的屬性或專門的模型的屬性。5.1. 屬性驅動:
屬性驅動就是屬性(property)作為貫穿MVC流程的資訊攜帶者。簡單的說,就是使用Action例項來封裝請求引數和處理結果資訊。前面我們做的示例都屬於屬性驅動模式。5.2. 模型驅動:
模型驅動就是使用單獨的javaBean作為貫穿整個MVC流程的資訊攜帶者。也就是說,使用單獨的VO(值物件)來封裝請求引數和處理結果資訊。 示例:繼續修改使用者登入驗證: 1、新增一使用者域模型物件:User.javapackage org.qiujy.domain; publicclass User { private String userName; private String password; /** *@returntheuserName */ public String getUserName() { returnuserName; } /** *@paramuserNametheuserNametoset */ publicvoid setUserName(String userName) { this.userName = userName; } /** *@returnthepassword */ public String getPassword() { returnpassword; } /** *@parampasswordthepasswordtoset */ publicvoid setPassword(String password) { this.password = password; } }
2、業務控制器:UserAction.java
package org.qiujy.web.struts2.action; import org.qiujy.domain.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; publicclass UserAction extends ActionSupport{ //定義用於封裝請求引數的模型物件 private User user = new User(); private String msg; //結果資訊屬性 /** *@returntheuser */ public User getUser() { returnuser; } /** *@paramusertheusertoset */ publicvoid setUser(User user) { this.user = user; } /** *@returnthemsg */ public String getMsg() { returnmsg; } /** *@parammsgthemsgtoset */ publicvoid setMsg(String msg) { this.msg = msg; } /** *處理使用者請求的login()方法 *@return結果導航字串 *@throwsException */ public String login() throws Exception{ String userName = user.getUserName(); String password = user.getPassword(); if("test".equals(userName) && "test".equals(password)){ msg = "登入成功,歡迎" + userName; //獲取ActionContext例項,通過它來訪問Servlet API ActionContext context = ActionContext.getContext(); //看session中是否已經存放了使用者名稱,如果存放了:說明已經登入了;否則說明是第一次登入成功 if(null != context.getSession().get("uName")){ msg = userName + ":你已經登入過了!!!"; }else{ context.getSession().put("uName", userName); } returnthis.SUCCESS; }else{ msg = "登入失敗,使用者名稱或密碼錯"; returnthis.ERROR; } } public String regist() throws Exception{ //將使用者名稱,密碼新增到資料庫中 //... msg = "註冊成功。"; returnthis.SUCCESS; } }
3、配置檔案:struts.xml
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="my" extends="struts-default" namespace="/manage"> <action name="userOpt" class="org.qiujy.web.struts2.action.UserAction"> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts>
4、頁面:index.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <html> <head> <title>使用者登入頁面</title> </head> <body> <h2>使用者入口</h2> <hr> <form action="manage/userOpt!login.action" method="post"> <table border="1"> <tr> <td>使用者名稱:</td> <td><input type="text" name="user.userName"/></td> </tr> <tr> <td>密碼:</td> <td><input type="password" name="user.password"/></td> </tr> <tr> <td colspan="2"> <input type="submit" value=" 確定 "/> </td> </tr> </table> </form> </body> </html>
其它頁面略。
5、執行效果:同以前一樣。 6、原始碼:6、Struts2的異常處理機制:
任何成熟的MVC框架都應該提供成就的異常處理機制。Strut2也不例外。Struts2提供了一種宣告式的異常處理方式。Struts2也是通過配置的攔截器來實現異常處理機制的。Struts2的異常處理機制通過在struts.xml檔案中配置<exception-mapping …>元素完成的,配置該元素時,需要指定兩個屬性: exception:此屬性指定該異常對映所設定的異常型別。 result:此屬性指定Action出現該異常時,系統轉入result屬性所指向的結果。6.1. 異常對映也分為兩種:
1)區域性異常對映:<exception-mapping…>元素作為<action…>元素的子元素配置。 2)全域性異常對映:<exception-mapping…>元素作為<global-exception-mappings>元素的子元素配置。6.2. 輸出異常資訊:
使用Struts2的標籤來輸出異常資訊: 1)<s:property value="exception.message"/> : 輸出異常物件本身。 2)<s:property value="exceptionStack"/> : 輸出異常堆疊資訊。6.3.示例:
還是修改使用者登入示例: 1) 把UserAciton.java中的regist方法改成:public String regist() throws Exception{ //將使用者名稱,密碼新增到資料庫中 //... //msg = "註冊成功。"; if(true){ throw new java.sql.SQLException("沒有資料庫驅動程式"); } return this.SUCCESS; }
2) 修改struts.xml檔案:
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="my" extends="struts-default" namespace="/manage"> <!-- 定義全域性處理結果 --> <global-results> <!-- 邏輯名為sql的結果,對映到/exception.jsp頁面 --> <result name="sql">/exception.jsp</result> </global-results> <global-exception-mappings> <!-- 當Action丟擲SQLException異常時,轉入名為sql的結果 --> <exception-mapping exception="java.sql.SQLException" result="sql"/> </global-exception-mappings> <action name="userOpt" class="org.qiujy.web.struts2.action.UserAction"> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts>
3) 新增一頁面:exception.jsp
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>異常資訊</title>
</head>
<body>
<h2>
出現異常啦
</h2>
<hr/>
<h3 style="color:red">
<!-- 獲得異常物件 -->
<s:property value="exception.message"/>
</h3>
<br/>
<!-- 異常堆疊資訊 -->
<s:property value="exceptionStack"/>
</html>
4) 執行regist.jsp進行除錯