struts框架具有組件的模塊化,靈活性和重用性的優點,同時簡化了基於MVC的web應用程序的開發。
一、Struts配置文件:struts-config.xml
1.配置global-forward:添加標籤,可以定義全局轉發,並不專屬於某個action。作用和標籤下的標籤是一樣的。通過創建邏輯名稱映射,實現JSP頁面的跳轉。
<global-forwards>
<forward name="index" path="/index.jsp"/>
</global-forwards>
2.配置form-beans:添加標籤,創建邏輯名稱映射ActionForm類。JSP頁面表單提交時,通過這些配置文件,將頁面數據映射並保存到相應的ActionForm類中。
<form-beans>
<form-bean name="loginForm" type="com.bjpowernode.struts.LoginActionForm"></form-bean>
</form-beans>
3.配置actionmappings:添加標籤,映射Action類,如果Action中用到ActionForm類,那麼會將Action和ActionForm類建立關聯。添加標籤控制轉向。
<action-mappings>
<action path="/login"
type="com.bjpowernode.struts.LoginAction"
name="loginForm"
scope="request"
>
<forward name="success" path="/login_success.jsp"></forward>
<forward name="error" path="/login_error.jsp"></forward>
</action>
</action-mappings>
二、ActionServlet類
struts框架中的控制器組件。這個類實現了javax.servlet.http.HttpServlet類,是Struts的Controller。
ActionServlet截取用戶的Http請求,把請求映射到相應的Action類上。並創建ActionForm類,調用Action的execute()方法,將ActionMapping對象,ActionForm Bean對象,request,response作爲參數傳遞過去。
1.ActionMapping類
通過截取用戶請求,在struts-config.xml中映射到特定Action的相關信息存儲在ActionMapping中。作爲Action類中execute()方法的一個參數。完成調用相應的邏輯處理類後,用ActionMapping的findForward()方法,完成轉發。
2.Action類
Action類真正實現了業務邏輯。所有的Action類都繼承org.apache.struts.action.Action類。並重寫了execute方法。
Action實現了線程安全,保證控制器面對多個用戶請求時共享一個實例。
3.ActionForward類
根據Action類的處理的結果,控制器跳轉到轉向頁面。
4.ActionForm類
struts框架中,爲表單創建了ActionForm Bean,在struts-config.xml文件中定義bean,並將其與Action關聯起來,會將form作爲參數傳遞到Action中。這樣Action中可以對其直接處理。
三、錯誤處理類
struts提供了兩個錯誤類:ActionErrors和ActionError,它們都集成org.apache.struts.action類。ActionErrors保存着ActionError對象的集合。其中每一個都代表了獨立的錯誤信息。