初學(xué)struts也是一知半解,比如action與dispatchAction的區(qū)別,最近便讓我十分困惑。
做為一個初學(xué)者,在目前使用過的東西中,主要有mapping.findForward(),action,dispatchAction三個實用功能,這三者放在一起本不太合適,但是在我看來,也有一定的相關(guān)性。
struts主要用途
1. 判斷url傳值所要做的操作。比如 http://www.baidu.com/index.jsp?run=showAll ,這個如果使用了action,可以使用request.getParameter()接收。
2. 使用mapping.findForward(url);替換servlet的response.sendRedirect("http://www.baidu.com");
3. 把form提交的內(nèi)容封裝到formBean。這樣在使用了大量form的時候,可以用formBean的一實例lf.formName這樣去調(diào)用。
好處在于不用使用request.getParameter("formName");去接收。
4. 使用dispatchAction,在struts-config.xml中進行配置,直接可以判斷get鏈接中的傳值,也可以避免使用request.getParameter("formName");去接收。
formBean與dispatchAction的區(qū)別:
顯而易見,formBean使用在大量的post表單的情況下。
dispatchAction常用來處理url鏈接中傳來的值。
Action與dispatchAction的區(qū)別:
這里使用區(qū)別并不合適,因為dispatchAction繼承自Action,所以dispatchAction是對action進行了功能的擴充,action常需要使用getParameter()先獲取傳入的值,再判斷這個值是否正常,再重定向到不同的頁面。
而dispatchAction把判斷放以了struts-config.xml文件中,而不需要再到業(yè)務(wù)層進行判斷。并且dispatchAction在使用中,更常用于處理url傳入的get請求。
Struts的生存周期
啟動web服務(wù)器 -- 加載web.xml文件 -- 產(chǎn)生ActionServlet實例 -- 加載struts-config.xml文件 -- 解析出多個action并放入actionMapping池
客戶端發(fā)現(xiàn)請求 -- web容器 -- 請求發(fā)送到ActionServlet -- 分發(fā)到不同的action并實例化 -- 模型層處理 -- 處理結(jié)果返回到actionServlet -- 返回結(jié)果到視圖層
舉例
下面是一個使用了dispatchAction的項目的完整struts-config.xml配置
---------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources />
<form-beans />
<global-exceptions />
<global-forwards />
<form-beans> //formbean的定義,name="loginForm"對應(yīng)于下文中的name="loginForm"
<form-bean name="loginForm" type="org.jsw.struts.form.LoginForm" />
</form-beans>
<action-mappings >
<action //定義了一個action
path="/manager" //此action的訪問路徑
name="loginForm" //此action用于接收哪個formbean,對應(yīng)于上文<form-beans>中的內(nèi)容
parameter="method" //此action用于接怍method的值,如果method值是add,那么自動調(diào)用業(yè)務(wù)層的add方法
type="com.umt.struts.action.ManagerAction">
<forward name="success" path="/success.jsp"></forward> //定義了重向向地址
<forward name="delete" path="/delete.jsp"></forward>
</action>
</action-mappings>
<message-resources parameter="com.jsw.struts.ApplicationResources" />
</struts-config>