一、在 src(classes) 目錄下新建 struts.xml,在 web.xml 中配置核心控制器(說白了就是一過濾器 ) org.apache.struts2.dispatcher.ng.filter.StrutsPRepareAndExecuteFilter
二、編寫 struts.xml,其大體結(jié)構(gòu)如下:
<package name= namespace= extends="struts-default"> <action name= class= method= > <result name= >xxx</result> </action></package>pageckage:方便管理動(dòng)作元素 name:必須有。包的名稱,配置文件中必須保證唯一。 namespace:該包的名稱空間,一般是以”/”開頭 extends:集成的父包的名稱。struts-default名稱的包是struts2框架已經(jīng)命名好的一個(gè)包。(在struts2-core.jar中有一個(gè)struts-default.xml中) abstract:是否是抽象包。沒有任何action元素的包就是抽象包(java類)
action:代表一個(gè)請(qǐng)求動(dòng)作 name:同包中必須唯一。動(dòng)作的名稱 class:負(fù)責(zé)處理的JavaBean的類全名 method:JavaBean中的對(duì)應(yīng)處理方法。(動(dòng)作方法:特點(diǎn)是,public String 方法名(){})
result:結(jié)果類型 name:動(dòng)作方法返回的字符串 主體內(nèi)容:View的具體地址。
三、根據(jù)配置文件,創(chuàng)建需要的javabean和對(duì)應(yīng)的動(dòng)作方法, 在動(dòng)作方法中完成你的邏輯調(diào)用。
public class HelloWorldAction extends ActionSupport implements Serializable { private static final long serialVersionUID = -3458082853638450597L; private String message; public String sayHello() { message = "Hello By Struts2!"; return SUCCESS; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; }}四、訪問helloworld動(dòng)作的方式: http://localhost:8080/struts2day01/test/helloworld   應(yīng)用名稱/包的名稱空間/動(dòng)作的名稱 默認(rèn)情況下:訪問動(dòng)作名helloworld,可以直接helloworld,或者h(yuǎn)elloworld.action
http://localhost:8080/struts2day01/test/a/b/c/helloworld /test/a/b/c:名稱空間 helloworld:動(dòng)作名稱 搜索順序:名稱空間 /test/a/b/c  沒有helloworld /test/a/b    沒有helloworld /test/a      沒有helloworld /test        有了,調(diào)用執(zhí)行
五、Struts2配置文件的詳解 Struts配置文件中的各種默認(rèn)值: action: class:默認(rèn)值是com.opensymphony.xwork2.ActionSupport method:默認(rèn)值是public String execute(){}
實(shí)際開發(fā)中:自己編寫的動(dòng)作類一般情況下繼承 com.opensymphony.xwork2.ActionSupport
result: type:轉(zhuǎn)到目的地的方式。默認(rèn)值是轉(zhuǎn)發(fā),名稱是dispatcher (注:type的取值是定義好的,不是瞎寫的。在struts-default.xml中的package中有定義)
dispatcher:普通的轉(zhuǎn)發(fā)到某個(gè)頁面 chain:普通的抓發(fā)到某個(gè)動(dòng)作名稱 redirect:重定向到一個(gè)頁面 redirectAction:重定向到一個(gè)動(dòng)作名稱 plainText:以純文本的形式輸出jsp內(nèi)容
result元素的寫法: 方式一: <result type="chain" name="success">a2</result> 方式二:
注意:如果要轉(zhuǎn)向的是在另外一個(gè)名稱空間的動(dòng)作,那么只能使用方式二
<package name="p1" namespace="/namespace1" extends="struts-default"> <action name="a2"> <result type="dispatcher" name="success">/3.jsp</result> </action></package><package name="p2" namespace="/namespace2" extends="struts-default"> <action name="a1"> <result type="chain" name="success"> <param name="namespace">/namespace1</param> <param name="actionName">a2</param> </result> </action></package>開發(fā)中配置文件的更改,在訪問時(shí)讓框架自動(dòng)重新加載: struts.devMode = false(org.apache.struts2/default.properties)
利用strutx.xml中的constant元素來覆蓋掉default.properties默認(rèn)行為
<struts> <constant name="struts.devMode" value="true"></constant></struts>新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注