介紹struts2框架
問題:什么是框架蛛淋,框架有什么用?
框架 是 實現(xiàn)部分功能的代碼 (半成品)环形,使用框架簡化企業(yè)級軟件開發(fā) ,提高開發(fā)效率蝌箍。
學(xué)習(xí)框架 ,清楚的知道框架能做什么善炫? 還有哪些工作需要自己編碼實現(xiàn) 雄驹?
問題:什么是struts2框架弥搞,它有什么用?
Struts 2是Struts的下一代產(chǎn)品,是在 struts 1和WebWork的技術(shù)基礎(chǔ)上進行了合并的全新的Struts 2框架烛谊。
其全新的Struts 2的體系結(jié)構(gòu)與Struts 1的體系結(jié)構(gòu)差別巨大。Struts 2以WebWork為核心
struts2=struts1+webwork;
struts2框架是apache產(chǎn)品环壤。
struts2是一個標(biāo)準(zhǔn)的mvc框架晒来。 javaweb中的model2模式就是一個mvc模式。 model2=servlet+jsp+javaBean
struts2框架是在javaweb開發(fā)中使用的郑现。
使用struts2框架湃崩,可以簡化我們的web開發(fā),并且降低程序的耦合度接箫。
類似于struts2框架的產(chǎn)品 :
struts1 webwork jsf springmvc
ssh---struts2 spring hibernate
ssi---springmvc spring ibatis
XWork---它是webwork核心
Xwork提供了很多核心功能:前端攔截機(interceptor)攒读,運行時表單屬性驗證,類型轉(zhuǎn)換辛友,
強大的表達(dá)式語言(OGNL – the Object Graph Navigation Language)薄扁,
IoC(Inversion of Control反轉(zhuǎn)控制)容器等
struts2快速入門:
index.jsp------>HelloServlet-------->hello.jsp web開發(fā)流程.
index.jsp------>HelloAction--------->hello.jsp struts2流程
1.導(dǎo)入jar包
下載struts2的jar包 struts-2.3.15.1-all 版本.
struts2的目錄結(jié)構(gòu):
apps: 例子程序
docs:文檔
lib:struts2框架所應(yīng)用的jar以及插件包
src:源代碼
core 它是struts2的源代碼
xwork-core struts2底層使用了xwork,xwork的源代碼
注意:在struts2開發(fā),一般情況下最少導(dǎo)入的jar包废累,去apps下的struts2-blank示例程序中copy
2.創(chuàng)建index.jsp頁面
創(chuàng)建hello.jsp頁面
3.對struts2框架進行配置
1.web.xml文件中配置前端控制器(核心控制器)-----就是一個Filter
目的:是為了讓struts2框架可以運行邓梅。
<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.創(chuàng)建一個struts.xml配置文件 ,這個是struts2框架配置文件。
目的:是為了struts2框架流程可以執(zhí)行邑滨。
名稱:struts.xml
位置:src下(classes下)
4.創(chuàng)建一個HelloAction類
要求日缨,在HelloAction類中創(chuàng)建一個返回值是String類型的方法,注意掖看,無參數(shù)匣距。
public String say(){
return "good";
}
5.在struts.xml文件中配置HelloAction
<package name="default" namespace="/" extends="struts-default">
<action name="hello" class="cn.itcast.action.HelloAction"
method="say">
<result name="good">/hello.jsp</result>
</action>
</package>
6.在index.jsp中添加連接,測試
<a href="${pageContext.request.contextPath}/hello">第一次使用struts2</a>
在地址欄中輸入:http://localhost/struts2_day01/index.jsp 訪問連接哎壳,就可以看到
HelloAction類中的say方法執(zhí)行了毅待,也跳轉(zhuǎn)到了hello.jsp.
struts流程圖
struts流程圖
模仿struts2流程完成入門程序:
index.jsp
hello.jsp
HelloAction
struts.xml
-----------------
1.創(chuàng)建一個Filter----StrutsFilter
2.在web.xml文件中配置StrutsFilter
<filter>
<filter-name>struts</filter-name>
<filter-class>cn.itcast.filter.StrutsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.在StrutsFilter中完成攔截操作,并訪問Action中的方法归榕,跳轉(zhuǎn)到hello.jsp頁面操作.
// 2.1 得到請求資源路徑
String uri = request.getRequestURI();
String contextPath = request.getContextPath();
String path = uri.substring(contextPath.length() + 1);
// System.out.println(path); // hello
// 2.2 使用path去struts.xml文件中查找某一個<action name=path>這個標(biāo)簽
SAXReader reader = new SAXReader();
// 得到struts.xml文件的document對象尸红。
Document document = reader.read(new File(this.getClass()
.getResource("/struts.xml").getPath()));
Element actionElement = (Element) document
.selectSingleNode("http://action[@name='" + path + "']"); // 查找<action
// name='hello'>這樣的標(biāo)簽
if (actionElement != null) {
// 得到<action>標(biāo)簽上的class屬性以及method屬性
String className = actionElement.attributeValue("class"); // 得到了action類的名稱
String methodName = actionElement.attributeValue("method");// 得到action類中的方法名稱。
// 2.3通過反射,得到Class對象驶乾,得到Method對象
Class actionClass = Class.forName(className);
Method method = actionClass.getDeclaredMethod(methodName);
// 2.4 讓method執(zhí)行.
String returnValue = (String) method.invoke(actionClass
.newInstance()); // 是讓action類中的方法執(zhí)行邑飒,并獲取方法的返回值。
// 2.5
// 使用returnValue去action下查找其子元素result的name屬性值级乐,與returnValue做對比疙咸。
Element resultElement = actionElement.element("result");
String nameValue = resultElement.attributeValue("name");
if (returnValue.equals(nameValue)) {
// 2.6得到了要跳轉(zhuǎn)的路徑。
String skipPath = resultElement.getText();
// System.out.println(skipPath);
request.getRequestDispatcher(skipPath).forward(request,
response);
return;
}
}
struts2的流程分析以及工具配置
1.流程分析
請求 ---- StrutsPrepareAndExecuteFilter 核心控制器 ----- Interceptors 攔截器(實現(xiàn)代碼功能 ) ----- Action 的execute --- 結(jié)果頁面 Result
* 攔截器 在 struts-default.xml定義
* 執(zhí)行攔截器 是 defaultStack 中引用攔截器
---- 通過源代碼級別斷點調(diào)試风科,證明攔截器是執(zhí)行
2.關(guān)于手動配置struts.xml文件中提示操作
如果安裝Aptana編輯器 撒轮,請不要用Aptana自帶xml編輯器 編寫struts2配置文件
struts.xml提示來自于 DTD約束,
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
如果可以上網(wǎng)贼穆,自動緩存dtd题山,提供提示功能
如果不能上網(wǎng),也可以配置本地DTD提示
*** 導(dǎo)入DTD時故痊,應(yīng)該和配置DTD版本一致
3.關(guān)聯(lián)struts2源文件
如果是com.opensymphony.xxx 在xwork-core下
如果是org.apache.struts2 在core下
4.使用插件 struts2-config-browser-plugin-2.3.15.1
提供在瀏覽器中查看 struts2 配置加載情況
將解壓struts2/lib/struts2-config-browser-plugin-2.3.7.jar 復(fù)制WEB-INF/lib下
訪問 http://localhost/struts2_day01/config-browser/index.action 查看 struts2配置加載情況
struts.xml提示配置
struts2配置文件加載順序
struts2框架要能執(zhí)行顶瞳,必須先加載StrutsPrepareAndExecuteFilter.
在StrutsPrepareAndExecuteFilter的init方法中對Dispatcher進行了初始化.
在Dispatcher類中定義的init方法內(nèi)就描述了struts2配置文件加載的順序
init_DefaultProperties(); // [1] ---------- org/apache/struts2/default.properties
init_TraditionalXmlConfigurations(); // [2] --- struts-default.xml,struts-plugin.xml,struts.xml
init_LegacyStrutsProperties(); // [3] --- 自定義struts.properties
init_CustomConfigurationProviders(); // [5] ----- 自定義配置提供
init_FilterInitParameters() ; // [6] ----- web.xml
init_AliasStandardObjects() ; // [7] ---- Bean加載
1.default.properties文件
作用:定義了struts2框架中所有常量
位置: org/apache/struts2/default.properties
2.struts-default.xml
作用:配置了bean,interceptor,result等。
位置:在struts的core核心jar包.
struts-plugin.xml
它是struts2框架中所使用的插件的配置文件愕秫。
struts.xml
我們使struts2所使用的配置文件慨菱。
3.自定義的struts.properties
就是可以自定義常量。
4.web.xml
在開發(fā)中戴甩,后加載文件中的配置會將先加載文件中的配置覆蓋符喝。
default.properties
struts-default.xml
struts.xml
Action的配置
1.<package> 作用:是用于聲明一個包。用于管理action甜孤。
1.name 它用于聲明一個包名协饲,包名不能重復(fù),也就是它是唯一的缴川。
2.namespace 它與action標(biāo)簽的name屬性合并確定了一個唯一訪問action的路徑茉稠。
3.extends 它代表繼承的包名。
4.abstrace 它可以取值為true/false,如果為true,代表這個包是用于被繼承的把夸。
2<action> 用于聲明 一個action
1.name 就是action的一個名稱而线,它是唯一的(在同包內(nèi)) 它與package中的namespace確定了訪問action的路徑。
2.class Action類的全名
3.method 要訪問的Action類中的方法的名稱,方法無參數(shù) 扎即,返回值為String.
3.<result> 用于確定返回結(jié)果類型
1.name 它與action中的方法返回值做對比,確定跳轉(zhuǎn)路徑况凉。
關(guān)于action配置其它細(xì)節(jié):
1.關(guān)于默認(rèn)值問題
<package namespace="默認(rèn)值"> namespace的默認(rèn)值是"/",namespace代表的就是資源的路徑
<action class="默認(rèn)值" method="默認(rèn)值">
class的默認(rèn)值是 com.opensymphony.xwork2.ActionSupport
method的默認(rèn)值是 execute
<result\d X name="默認(rèn)值"> name的默認(rèn)值是 "success"
2.關(guān)于訪問action的路徑問題
現(xiàn)在的action的配置是:
<package name="default" namespace="/" extends="struts-default">
<action name="hello" class="cn.itcast.action.DefaultAction">
<result>/hello.jsp</result>
</action>
</package>
當(dāng)我們輸入:
http://localhost/struts2_day01_2/a/b/c/hello
也訪問到了action谚鄙。
原因:struts2中的action被訪問時,它會首先查找
1.namespace="/a/b/c" action的name=hello 沒有.
2.namespace="/a/b action的name=hello 沒有
3.namespace="/a" action的name=hello 沒有
4.namespace="/" action的name=hello 查找到了.
如果最后也查找不到刁绒,會報404錯誤.
3.默認(rèn)的action闷营。
作用:處理其它action處理不了的路徑。
<default-action-ref name="action的名稱" />
配置了這個,當(dāng)訪問的路徑傻盟,其它的action處理不了時速蕊,就會執(zhí)行name指定的名稱的action。
4.action的默認(rèn)處理類
在action配置時娘赴,如果class不寫规哲。默認(rèn)情況下是 com.opensymphony.xwork2.ActionSupport。
<default-class-ref class="cn.itcast.action.DefaultAction"/>
如果設(shè)置了诽表,那么在當(dāng)前包下唉锌,默認(rèn)處理action請的的處理類就為class指定的類。
關(guān)于常量配置
default.properties 它聲明了struts中的常量竿奏。
問題:人為設(shè)置常量袄简,可以在哪些位置設(shè)置 ?
1.struts.xml(應(yīng)用最多)
<constant name="常量名稱" value="常量值"></constant>
2.struts.properties(基本不使用)
3.web.xml(了解)
配置常量泛啸,是使用StrutsPrepareAndExecuteFilter的初始化參數(shù)來配置的.
<init-param>
<param-name>struts.action.extension</param-name>
<param-value>do,,</param-value>
</init-param>
常用常量
struts.action.extension=action,,
這個常量用于指定strus2框架默認(rèn)攔截的后綴名.
<constant name="struts.i18n.encoding" value="UTF-8"/>
相當(dāng)于request.setCharacterEncoding("UTF-8"); 解決post請求亂碼
<constant name="struts.serve.static.browserCache" value="false"/>
false不緩存绿语,true瀏覽器會緩存靜態(tài)內(nèi)容,產(chǎn)品環(huán)境設(shè)置true候址、開發(fā)環(huán)境設(shè)置false
<constant name="struts.devMode" value="true" />
提供詳細(xì)報錯頁面吕粹,修改struts.xml后不需要重啟服務(wù)器 (要求)
struts.xml文件的分離:
目的:就是為了閱讀方便∽诠停可以讓一個模塊一個配置文件昂芜,在struts.xml文件中通過
<include file="test.xml"/>導(dǎo)入其它的配置文件。
Action
1.關(guān)于Action類的創(chuàng)建方式介紹:
有三種方式
1.創(chuàng)建一個POJO類.
簡單的Java對象(Plain Old Java Objects)
指的是沒有實現(xiàn)任何接口赔蒲,沒有繼承任何父類(除了Object)
優(yōu)點:無耦合泌神。
缺點:所以工作都要自己實現(xiàn)。
在struts2框架底層是通過反射來操作:
* struts2框架 讀取struts.xml 獲得 完整Action類名
* obj = Class.forName("完整類名").newInstance();
* Method m = Class.forName("完整類名").getMethod("execute"); m.invoke(obj); 通過反射 執(zhí)行 execute方法
2.創(chuàng)建一個類舞虱,實現(xiàn)Action接口. com.opensymphony.xwork2.Action
優(yōu)點:耦合低欢际。提供了五種結(jié)果視圖,定義了一個行為方法矾兜。
缺點:所以工作都要自己實現(xiàn)损趋。
public static final String SUCCESS = "success"; // 數(shù)據(jù)處理成功 (成功頁面)
public static final String NONE = "none"; // 頁面不跳轉(zhuǎn) return null; 效果一樣
public static final String ERROR = "error"; // 數(shù)據(jù)處理發(fā)送錯誤 (錯誤頁面)
public static final String INPUT = "input"; // 用戶輸入數(shù)據(jù)有誤,通常用于表單數(shù)據(jù)校驗 (輸入頁面)
public static final String LOGIN = "login"; // 主要權(quán)限認(rèn)證 (登陸頁面)
3.創(chuàng)建一個類椅寺,繼承自ActionSupport類. com.opensymphony.xwork2.ActionSupport
ActionSupport類實現(xiàn)了Action接口浑槽。
優(yōu)點:表單校驗、錯誤信息設(shè)置返帕、讀取國際化信息 三個功能都支持.
缺點:耦合度高桐玻。
在開發(fā)中,第三種會使用的比較多.
關(guān)于action的訪問:
1.通過設(shè)置method的值荆萤,來確定訪問action類中的哪一個方法.
<action name="book_add" class="cn.itcast.action.BookAction" method="add"></action>
當(dāng)訪問的是book_add,這時就會調(diào)用BookAction類中的add方法镊靴。
<action name="book_update" class="cn.itcast.action.BookAction" method="update"></action>
當(dāng)訪問的是book_update,這時就會調(diào)用BookAction類中的update方法铣卡。
2.使用通配符來簡化配置
1.在struts.xml文件中
<action name="*_*" class="cn.itcast.action.{1}Action" method="{2}"></action>
2.在jsp頁面上
book.jsp
<a href="${pageContext.request.contextPath}/Book_add">book add</a><br>
<a href="${pageContext.request.contextPath}/Book_update">book update</a><br>
<a href="${pageContext.request.contextPath}/Book_delete">book delete</a><br>
<a href="${pageContext.request.contextPath}/Book_search">book search</a><br>
product.jsp
<a href="${pageContext.request.contextPath}/Product_add">product add</a><br>
<a href="${pageContext.request.contextPath}/Product_update">product update</a><br>
<a href="${pageContext.request.contextPath}/Product_delete">product delete</a><br>
<a href="${pageContext.request.contextPath}/Product_search">product search</a><br>
當(dāng)訪問book add時,這時的路徑是 Book_add,那么對于struts.xml文件中.
第一個星就是 Book
第二個星就是 add
對于{1}Action---->BookAction
對于method={2}--->method=add
使用通配符來配置注意事項:
1.必須定義一個統(tǒng)一的命名規(guī)范偏竟。
2.不建議使用過多的通配符煮落,閱讀不方便。
3.動態(tài)方法調(diào)用 (了解)
在struts.xml文件中
<action name="book" class="cn.itcast.action.BookAction"></action>
訪問時路徑: http://localhost/struts2_day01_2/book!add
就訪問到了BookAction類中的add方法踊谋。
對于book!add 這就是動態(tài)方法調(diào)用蝉仇。
注意:struts2框架支持動態(tài)方法調(diào)用,是因為在default.properties配置文件中設(shè)置了
動態(tài)方法調(diào)用為true.
struts.enable.DynamicMethodInvocation = true
在struts2框架中獲取servlet api
對于struts2框架褪子,不建議直接使用servlet api;
在struts2中獲取servlet api有三種方式:
1.通過ActionContext來獲取
1.獲取一個ActionContext對象量淌。
ActionContext context=ActionContext.getContext();
2.獲取servlet api
注意:通過ActionContext獲取的不是真正的Servlet api,而是一個Map集合。
1.context.getApplication()
2.context.getSession()
3.context.getParameter();---得到的就相當(dāng)于request.getParameterMap()
4.context.put(String,Object) 相當(dāng)于request.setAttribute(String,String);
2.注入方式獲取(這種方式是真正的獲取到了servlet api)
1.要求action類必須實現(xiàn)提定接口嫌褪。
ServletContextAware : 注入ServletContext對象
ServletRequestAware :注入 request對象
ServletResponseAware : 注入response對象
2.重定接口中的方法呀枢。
private HttpServletRequest request;
3.聲明一個web對象,使用接口中的方法的參數(shù)對聲明的web對象賦值.
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
擴展:分析其實現(xiàn):
是使用struts2中的一個interceptor完成的.
<interceptor name="servletConfig" class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>
if (action instanceof ServletRequestAware) { //判斷action是否實現(xiàn)了ServletRequestAware接口
HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST); //得到request對象.
((ServletRequestAware) action).setServletRequest(request);//將request對象通過action中重寫的方法注入笼痛。
}
3.通過ServletActionContext獲取.
在ServletActionContext中方法都是static裙秋。
getRequest();
getResposne();
getPageContext();
Result結(jié)果類型
<result>標(biāo)簽
1.name 與action中的method的返回值匹配,進行跳轉(zhuǎn).
2.type 作用:是用于定義跳轉(zhuǎn)方式
對于type屬性它的值有以下幾種:
在struts-default.xml文件中定義了type可以取的值
<result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>
<result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>
<result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/>
<result-type name="httpheader" class="org.apache.struts2.dispatcher.HttpHeaderResult"/>
<result-type name="redirect" class="org.apache.struts2.dispatcher.ServletRedirectResult"/>
<result-type name="redirectAction" class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>
<result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
<result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/>
<result-type name="xslt" class="org.apache.struts2.views.xslt.XSLTResult"/>
<result-type name="plainText" class="org.apache.struts2.dispatcher.PlainTextResult" />
必會: chain dispatcher redirect redirectAction stream
dispatcher:它代表的是請求轉(zhuǎn)發(fā)缨伊,也是默認(rèn)值摘刑。它一般用于從action跳轉(zhuǎn)到頁面。
chain:它也相當(dāng)于請求轉(zhuǎn)發(fā)刻坊。它一般情況下用于從一個action跳轉(zhuǎn)到另一個action枷恕。
redirect:它代表的是重定向 它一般用于從action跳轉(zhuǎn)到頁面
redirectAction: 它代表的是重定向 它一般用于從action跳轉(zhuǎn)另一個action。
stream:代表的是服務(wù)器端返回的是一個流谭胚,一般用于下載徐块。
了解: freemarker velocity
局部結(jié)果頁面與全局結(jié)果頁面
局部結(jié)果頁面 和 全局結(jié)果頁面
<action name="result" class="cn.itcast.struts2.demo6.ResultAction">
<!-- 局部結(jié)果 當(dāng)前Action使用 -->
<result name="success">/demo6/result.jsp</result>
</action>
<global-results>
<!-- 全局結(jié)果 當(dāng)前包中 所有Action都可以用-->
<result name="success">/demo6/result.jsp</result>
</global-results>