【Struts2學習筆記(5)】Struts2的處理流程及工作原理,struts2學習筆記
(1)Struts2的處理流程
(2)處理功能
1.StrutsPrepareAndExecuteFilter是Struts 2架構的核心控制器(在Struts 2.1.3以後 ,使用org.apache.struts2.dispatcher.FilterDispatcher已經標記為過時),它負責攔截由<url-pattern>/*</url-pattern>指定的所有使用者請求,
2.當使用者請求到達時,該Filter會過濾使用者的請求。預設情況下,如果使用者請求的路徑不帶尾碼或者尾碼以.action結尾,這時請求將被轉入Struts 2架構處理,
否則Struts 2架構將略過該請求的處理。當請求轉入Struts 2架構處理時會先經過一系列的攔截器,然後再到Action。與Struts1不同,
Struts2對使用者的每一次請求都會建立一個Action,所以Struts2中的Action是安全執行緒的。
(3)Struts2的web.xml檔案
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><display-name></display-name><!-- 是在struts2-core-2.1.8jar包下的 org.apache.struts2.dispatcher.ng.filter下邊的 StrutsPrepareAndExecuteFilter類 --><!-- 在Struts 2.1.3以後 使用org.apache.struts2.dispatcher.FilterDispatcher已經標記為過時 --><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><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>
(4)為應用指定多個struts設定檔在大部分應用裡,隨著應用規模的增加,系統中Action的數量也會大量增加,導致struts.xml設定檔變得非常臃腫。為了避免struts.xml檔案過於龐大、臃腫,提高struts.xml檔案的可讀性,我們可以將一個struts.xml設定檔分解成多個設定檔,然後在struts.xml檔案中包含其他設定檔。下面的struts.xml通過<include>元素指定多個設定檔:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"><struts><include file="struts-user.xml"/><include file="struts-order.xml"/></struts>
通過這種方式,我們就可以將Struts 2的Action按模組添加在多個設定檔中。
Struts2的工作原理,簡單點說出來
Struts2流程
1、用戶端發送請求 (用戶端初始化一個指向Servlet容器(如Tomcat)的請求)
2、請求經過一系列過濾器(如ActionContextCleanUp、SiteMesh等),ActionContextCleanUp-->FilterDispatcher
3、FilterDispatcher通過ActionMapper來決定這個Request需要調用哪個Action
4、如果ActionMapper決定調用某個Action,FilterDispatcher把請求的處理交給ActionProxy,
5、ActionProxy通過ConfigurationManager詢問Struts設定檔(Struts.xml),找到需要調用的Action類。
6、ActionProxy建立一個ActionInvocation的執行個體
7、ActionInvocation調用真正的Action,當然這涉及到相關攔截器的調用(interceptor)
8、Action執行完畢,ActionInvocation建立Result並返回,返回結果前要做些動作也是可以的
struts2的處理流程?
1、用戶端向Servlet容器(如Tomcat)提交一個請求
2、請求經過一系列過濾器(如ActionContextCleanUp (已被JVM和WEB容器廢棄的Null 物件) 過濾器等)
3、核心控制器被調用,詢問ActionMapper來決定請求是否需要調用某個Action
4、如果ActionMapper決定需要調用某個Action,核心控制器把控制權委派給ActionProxy (備忘:JSP請求無需調用Action)
5、ActionProxy通過Configuration Manager詢問架構的設定檔(struts.xml),找到需調用的Action類
6、ActionProxy建立一個ActionInvocation的執行個體,(ActionInvocation的作用是如何執行Action,攔截器的功能就是在ActionInvocation中實現的)
7、ActionInvocation負責調用Action,在此之前會依次調用所有配置的攔截器
8、Action執行完畢,ActionInvocation負責根據結果碼字串在struts.xml的配置中找到對應的返回結果
9、攔截器被再次執行
10、過濾器被再次執行