Struts2源碼閱讀--請求流程

[img][/img]Struts包介紹

(http://www.blogjava.net/lzhidj/archive/2008/07/10/213898.html)(大部分敘述性的文字和圖從其文中拷貝): 包名
說明

org.apache.struts2. components
該包封裝視圖組件,Struts2在視圖組件上有了很大加強,不僅增加了組件的屬性個數,更新增了幾個非常有用的組件,如updownselect、doubleselect、datetimepicker、token、tree等。

另外,Struts2可視化視圖組件開始支持主題(theme),缺省情況下,使用自帶的缺省主題,如果要自定義頁面效果,需要將組件的theme屬性設置爲simple。

org.apache.struts2. config
該包定義與配置相關的接口和類。實際上,工程中的xml和properties文件的讀取和解析都是由WebWork完成的,Struts只做了少量的工作。

org.apache.struts2.dispatcher
Struts2的核心包,最重要的類都放在該包中。

org.apache.struts2.impl
該包只定義了3個類,他們是StrutsActionProxy、StrutsActionProxyFactory、StrutsObjectFactory,這三個類都是對xwork的擴展。

org.apache.struts2.interceptor
定義內置的截攔器。

org.apache.struts2.util
實用包。

org.apache.struts2.validators
只定義了一個類:DWRValidator。

org.apache.struts2.views
提供freemarker、jsp、velocity等不同類型的頁面呈現。


下表是對一些重要類的說明:

類名
說明

org.apache.struts2.dispatcher. Dispatcher
該類有兩個作用:

1、初始化

2、調用指定的Action的execute()方法。

org.apache.struts2.dispatcher. FilterDispatcher
這是一個過濾器。文檔中已明確說明,如果沒有經驗,配置時請將url-pattern的值設成/*。

該類有四個作用:

1、執行Action

2、清理ActionContext,避免內存泄漏

3、處理靜態內容(Serving static content)

4、爲請求啓動xwork’s的截攔器鏈。

com.opensymphony.xwork2. ActionProxy
Action的代理接口。

com.opensymphony.xwork2. ctionProxyFactory
生產ActionProxy的工廠。

com.opensymphony.xwork2.ActionInvocation
負責調用Action和截攔器。

com.opensymphony.xwork2.config.providers. XmlConfigurationProvider
負責Struts2的配置文件的解析。



Struts體系結構

Struts工作機制
1、客戶端初始化一個指向Servlet容器(例如Tomcat)的請求;
2、這個請求經過一系列的過濾器(Filter)(這些過濾器中有一個叫做ActionContextCleanUp的可選過濾器,這個過濾器對於Struts2和其他框架的集成很有幫助,例如:SiteMesh Plugin);
3、接着FilterDispatcher被調用,FilterDispatcher詢問ActionMapper來決定這個請求是否需要調用某個Action;
4、如果ActionMapper決定需要調用某個Action,FilterDispatcher把請求的處理交給ActionProxy;
5、ActionProxy通過Configuration Manager詢問框架的配置文件,找到需要調用的Action類;
6、ActionProxy創建一個ActionInvocation的實例。
7、ActionInvocation實例使用命名模式來調用,在調用Action的過程前後,涉及到相關攔截器(Intercepter)的調用。
8、一旦Action執行完畢,ActionInvocation負責根據struts.xml中的配置找到對應的返回結果。返回結果通常是(但不總是,也可能是另外的一個Action鏈)一個需要被表示的JSP或者FreeMarker的模版。在表示的過程中可以使用Struts2 框架中繼承的標籤。在這個過程中需要涉及到ActionMapper。
Struts源碼分析
從org.apache.struts2.dispatcher.FilterDispatcher開始


//創建Dispatcher,此類是一個Delegate,它是真正完成根據url解析,讀取對應Action。。。的地方
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;

dispatcher = createDispatcher(filterConfig);
dispatcher.init();
//讀取初始參數pakages,調用parse(),解析成類似/org/apache/struts2/static,/template的數組
String param = filterConfig.getInitParameter("packages");
String packages = "org.apache.struts2.static template org.apache.struts2.interceptor.debugging";
if (param != null) {
packages = param + " " + packages;
}
this.pathPrefixes = parse(packages);
}
顧名思義,init方法裏就是初始讀取一些屬性配置文件,先看init_DefaultProperties。
public void init() {

if (configurationManager == null) {
configurationManager = new ConfigurationManager(BeanSelectionProvider.DEFAULT_BEAN_NAME);
}

init_DefaultProperties(); // [1]
init_TraditionalXmlConfigurations(); // [2]
init_LegacyStrutsProperties(); // [3]
init_ZeroConfiguration(); // [4]
init_CustomConfigurationProviders(); // [5]
init_MethodConfigurationProvider();
init_FilterInitParameters() ; // [6]
init_AliasStandardObjects() ; // [7]

Container container = init_PreloadConfiguration();
init_CheckConfigurationReloading(container);
init_CheckWebLogicWorkaround(container);

}
private void init_DefaultProperties() {
configurationManager.addConfigurationProvider(new DefaultPropertiesProvider());
}
//DefaultPropertiesProvider
public void register(ContainerBuilder builder, LocatableProperties props)
throws ConfigurationException {

Settings defaultSettings = null;
try {
defaultSettings = new PropertiesSettings("org/apache/struts2/default");
} catch (Exception e) {
throw new ConfigurationException("Could not find or error in org/apache/struts2/default.properties", e);
}

loadSettings(props, defaultSettings);
}
//PropertiesSettings
//讀取org/apache/struts2/default.properties的配置信息,如果項目中需要覆蓋,可以在classpath裏的struts.properties裏覆寫
public PropertiesSettings(String name) {

URL settingsUrl = ClassLoaderUtils.getResource(name + ".properties", getClass());

if (settingsUrl == null) {
LOG.debug(name + ".properties missing");
settings = new LocatableProperties();
return;
}
//settings的類型爲LocatableProperties,繼承Properties
settings = new LocatableProperties(new LocationImpl(null, settingsUrl.toString()));

// Load settings
InputStream in = null;
try {
in = settingsUrl.openStream();
settings.load(in);
} catch (IOException e) {
throw new StrutsException("Could not load " + name + ".properties:" + e, e);
} finally {
if(in != null) {
try {
in.close();
} catch(IOException io) {
LOG.warn("Unable to close input stream", io);
}
}
}
}

再來看init_TraditionalXmlConfigurations方法,這個是讀取Action配置的方法。
private void init_TraditionalXmlConfigurations() {
//首先讀取web.xml中的config初始參數值
//如果沒有配置就使用默認的"struts-default.xml,struts-plugin.xml,struts.xml",
//這兒就可以看出爲什麼默認的配置文件必須取名爲這三個名稱了
//如果不想使用默認的名稱,直接在web.xml中配置config初始參數即可
String configPaths = initParams.get("config");
if (configPaths == null) {
configPaths = DEFAULT_CONFIGURATION_PATHS;
}
String[] files = configPaths.split("\\s*[,]\\s*");
//依次解析配置文件,xwork.xml單獨解析
for (String file : files) {
if (file.endsWith(".xml")) {
if ("xwork.xml".equals(file)) {
configurationManager.addConfigurationProvider(new XmlConfigurationProvider(file, false));
} else {
configurationManager.addConfigurationProvider(new StrutsXmlConfigurationProvider(file, false, servletContext));
}
} else {
throw new IllegalArgumentException("Invalid configuration file name");
}
}
}
對於其它配置文件只用StrutsXmlConfigurationProvider,此類繼承XmlConfigurationProvider,而XmlConfigurationProvider又實現ConfigurationProvider接口。類XmlConfigurationProvider負責配置文件的讀取和解析,addAction()方法負責讀取<action>標籤,並將數據保存在ActionConfig中;addResultTypes()方法負責將<result-type>標籤轉化爲ResultTypeConfig對象;loadInterceptors()方法負責將<interceptor>標籤轉化爲InterceptorConfi對象;loadInterceptorStack()方法負責將<interceptor-ref>標籤轉化爲InterceptorStackConfig對象;loadInterceptorStacks()方法負責將<interceptor-stack>標籤轉化成InterceptorStackConfig對象。而上面的方法最終會被addPackage()方法調用,將所讀取到的數據彙集到PackageConfig對象中。
protected PackageConfig addPackage(Element packageElement) throws ConfigurationException {
PackageConfig.Builder newPackage = buildPackageContext(packageElement);

if (newPackage.isNeedsRefresh()) {
return newPackage.build();
}

if (LOG.isDebugEnabled()) {
LOG.debug("Loaded " + newPackage);
}

// add result types (and default result) to this package
addResultTypes(newPackage, packageElement);

// load the interceptors and interceptor stacks for this package
loadInterceptors(newPackage, packageElement);

// load the default interceptor reference for this package
loadDefaultInterceptorRef(newPackage, packageElement);

// load the default class ref for this package
loadDefaultClassRef(newPackage, packageElement);

// load the global result list for this package
loadGlobalResults(newPackage, packageElement);

// load the global exception handler list for this package
loadGobalExceptionMappings(newPackage, packageElement);

// get actions
NodeList actionList = packageElement.getElementsByTagName("action");

for (int i = 0; i < actionList.getLength(); i++) {
Element actionElement = (Element) actionList.item(i);
addAction(actionElement, newPackage);
}

// load the default action reference for this package
loadDefaultActionRef(newPackage, packageElement);

PackageConfig cfg = newPackage.build();
configuration.addPackageConfig(cfg.getName(), cfg);
return cfg;
}
這兒發現一個配置上的小東西,我的xwork2.0.*是沒有的,但是看源碼是看到xwork2.1.*是可以的。看如下代碼:
private List loadConfigurationFiles(String fileName, Element includeElement) {
List<Document> docs = new ArrayList<Document>();
if (!includedFileNames.contains(fileName)) {
...........
Element rootElement = doc.getDocumentElement();
NodeList children = rootElement.getChildNodes();
int childSize = children.getLength();

for (int i = 0; i < childSize; i++) {
Node childNode = children.item(i);

if (childNode instanceof Element) {
Element child = (Element) childNode;

final String nodeName = child.getNodeName();
//解析每個action配置是,對於include文件可以使用通配符*來進行配置
//如Struts.xml中可配置成<include file="actions_*.xml"/>
if (nodeName.equals("include")) {
String includeFileName = child.getAttribute("file");
if(includeFileName.indexOf('*') != -1 ) {
// handleWildCardIncludes(includeFileName, docs, child);
ClassPathFinder wildcardFinder = new ClassPathFinder();
wildcardFinder.setPattern(includeFileName);
Vector<String> wildcardMatches = wildcardFinder.findMatches();
for (String match : wildcardMatches) {
docs.addAll(loadConfigurationFiles(match, child));
}
}
else {

docs.addAll(loadConfigurationFiles(includeFileName, child));
}
}
}
}
docs.add(doc);
loadedFileUrls.add(url.toString());
}
}
return docs;
}
init_CustomConfigurationProviders方式初始自定義的Provider,配置類全名和實現ConfigurationProvider接口就可以。
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {


HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
ServletContext servletContext = getServletContext();

String timerKey = "FilterDispatcher_doFilter: ";
try {
UtilTimerStack.push(timerKey);
//根據content type來使用不同的Request封裝,可以參見Dispatcher的wrapRequest
request = prepareDispatcherAndWrapRequest(request, response);
ActionMapping mapping;
try {
//根據url取得對應的Action的配置信息--ActionMapping,actionMapper是通過Container的inject注入的
mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());
} catch (Exception ex) {
LOG.error("error getting ActionMapping", ex);
dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
return;
}

//如果找不到對應的action配置,則直接返回。比如你輸入***.jsp等等
//這兒有個例外,就是如果path是以“/struts”開頭,則到初始參數packages配置的包路徑去查找對應的靜態資源並輸出到頁面流中,當然.class文件除外。如果再沒有則跳轉到404
if (mapping == null) {
// there is no action in this request, should we look for a static resource?
String resourcePath = RequestUtils.getServletPath(request);

if ("".equals(resourcePath) && null != request.getPathInfo()) {
resourcePath = request.getPathInfo();
}

if (serveStatic && resourcePath.startsWith("/struts")) {
String name = resourcePath.substring("/struts".length());
findStaticResource(name, request, response);
} else {
// this is a normal request, let it pass through
chain.doFilter(request, response);
}
// The framework did its job here
return;
}
//正式開始執行Action的方法了
dispatcher.serviceAction(request, response, servletContext, mapping);

} finally {
try {
ActionContextCleanUp.cleanUp(req);
} finally {
UtilTimerStack.pop(timerKey);
}
}
}
來看Dispatcher類的serviceAction方法:
public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,
ActionMapping mapping) throws ServletException {

Map<String, Object> extraContext = createContextMap(request, response, mapping, context);

// If there was a previous value stack, then create a new copy and pass it in to be used by the new Action
ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
if (stack != null) {
extraContext.put(ActionContext.VALUE_STACK, ValueStackFactory.getFactory().createValueStack(stack));
}

String timerKey = "Handling request from Dispatcher";
try {
UtilTimerStack.push(timerKey);
String namespace = mapping.getNamespace();
String name = mapping.getName();
String method = mapping.getMethod();

Configuration config = configurationManager.getConfiguration();
ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(namespace, name, extraContext, true, false);
proxy.setMethod(method);
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());

// if the ActionMapping says to go straight to a result, do it!
if (mapping.getResult() != null) {
Result result = mapping.getResult();
result.execute(proxy.getInvocation());
} else {
proxy.execute();
}

// If there was a previous value stack then set it back onto the request
if (stack != null) {
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
}
} catch (ConfigurationException e) {
LOG.error("Could not find action or result", e);
sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);
} catch (Exception e) {
throw new ServletException(e);
} finally {
UtilTimerStack.pop(timerKey);
}
}
第一句createContextMap()方法,該方法主要把Application、Session、Request的key value值拷貝到Map中,並放在HashMap<String,Object>中,可以參見createContextMap方法:
public HashMap<String,Object> createContextMap(Map requestMap,
Map parameterMap,
Map sessionMap,
Map applicationMap,
HttpServletRequest request,
HttpServletResponse response,
ServletContext servletContext) {
HashMap<String,Object> extraContext = new HashMap<String,Object>();
extraContext.put(ActionContext.PARAMETERS, new HashMap(parameterMap));
extraContext.put(ActionContext.SESSION, sessionMap);
extraContext.put(ActionContext.APPLICATION, applicationMap);

Locale locale;
if (defaultLocale != null) {
locale = LocalizedTextUtil.localeFromString(defaultLocale, request.getLocale());
} else {
locale = request.getLocale();
}

extraContext.put(ActionContext.LOCALE, locale);
//extraContext.put(ActionContext.DEV_MODE, Boolean.valueOf(devMode));

extraContext.put(StrutsStatics.HTTP_REQUEST, request);
extraContext.put(StrutsStatics.HTTP_RESPONSE, response);
extraContext.put(StrutsStatics.SERVLET_CONTEXT, servletContext);

// helpers to get access to request/session/application scope
extraContext.put("request", requestMap);
extraContext.put("session", sessionMap);
extraContext.put("application", applicationMap);
extraContext.put("parameters", parameterMap);

AttributeMap attrMap = new AttributeMap(extraContext);
extraContext.put("attr", attrMap);

return extraContext;
}
後面纔是最主要的--ActionProxy,ActionInvocation。ActionProxy是Action的一個代理類,也就是說Action的調用是通過ActionProxy實現的,其實就是調用了ActionProxy.execute()方法,而該方法又調用了ActionInvocation.invoke()方法。歸根到底,最後調用的是DefaultActionInvocation.invokeAction()方法。先看DefaultActionInvocation的init方法。
public void init(ActionProxy proxy) {
this.proxy = proxy;
Map contextMap = createContextMap();
//設置ActionContext,把ActionInvocation和Action壓入ValueStack
ActionContext actionContext = ActionContext.getContext();

if(actionContext != null) {
actionContext.setActionInvocation(this);
}
//創建Action,可以看出Struts2裏是每次請求都新建一個Action,careateAction方法可以自己參考
createAction(contextMap);
if (pushAction) {
stack.push(action);
contextMap.put("action", action);
}
invocationContext = new ActionContext(contextMap);
invocationContext.setName(proxy.getActionName());
List interceptorList = new ArrayList(proxy.getConfig().getInterceptors());
interceptors = interceptorList.iterator();
}
protected void createAction(Map contextMap) {

String timerKey = "actionCreate: "+proxy.getActionName();
try {
UtilTimerStack.push(timerKey);
//這兒默認建立Action是StrutsObjectFactory,實際中我使用的時候都是使用Spring創建的Action,這個時候使用的是SpringObjectFactory
action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);
}
.......
catch (Exception e) {
........
throw new XWorkException(gripe, e, proxy.getConfig());
} finally {
UtilTimerStack.pop(timerKey);
}

if (actionEventListener != null) {
action = actionEventListener.prepare(action, stack);
}
}
接下來看看DefaultActionInvocation 的invoke方法。
public String invoke() throws Exception {
String profileKey = "invoke: ";
try {
UtilTimerStack.push(profileKey);

if (executed) {
throw new IllegalStateException("Action has already executed");
}
//先執行interceptors
if (interceptors.hasNext()) {
final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();
UtilTimerStack.profile("interceptor: "+interceptor.getName(),
new UtilTimerStack.ProfilingBlock<String>() {
public String doProfiling() throws Exception {
resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
return null;
}
});
} else {
//interceptor執行完了之後執行action
resultCode = invokeActionOnly();
}

if (!executed) {
if (preResultListeners != null) {
for (Iterator iterator = preResultListeners.iterator();
iterator.hasNext();) {
PreResultListener listener = (PreResultListener) iterator.next();

String _profileKey="preResultListener: ";
try {
UtilTimerStack.push(_profileKey);
listener.beforeResult(this, resultCode);
}
finally {
UtilTimerStack.pop(_profileKey);
}
}
}

// now execute the result, if we're supposed to
if (proxy.getExecuteResult()) {
executeResult();
}

executed = true;
}

return resultCode;
}
finally {
UtilTimerStack.pop(profileKey);
}
}
看程序中的if(interceptors.hasNext())語句,當然,interceptors裏存儲的是interceptorMapping列表(它包括一個Interceptor和一個name),所有的截攔器必須實現Interceptor的intercept方法,而該方法的參數恰恰又是ActionInvocation,在intercept方法中還是調用invocation.invoke(),從而實現了一個Interceptor鏈的調用。當所有的Interceptor執行完,最後調用invokeActionOnly方法來執行Action相應的方法。
protected String invokeAction(Object action, ActionConfig actionConfig) throws Exception {
String methodName = proxy.getMethod();

String timerKey = "invokeAction: "+proxy.getActionName();
try {
UtilTimerStack.push(timerKey);

boolean methodCalled = false;
Object methodResult = null;
Method method = null;
try {
//獲得Action對應的方法
method = getAction().getClass().getMethod(methodName, new Class[0]);
} catch (NoSuchMethodException e) {

try {
//如果沒有對應的方法,則使用do+Xxxx來再次獲得方法
String altMethodName = "do" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
method = getAction().getClass().getMethod(altMethodName, new Class[0]);
} catch (NoSuchMethodException e1) {
.....
}
}

if (!methodCalled) {
methodResult = method.invoke(action, new Object[0]);
}
//根據不同的Result類型返回不同值
if (methodResult instanceof Result) {
this.explicitResult = (Result) methodResult;
return null;
} else {
return (String) methodResult;
}
}
....
} finally {
UtilTimerStack.pop(timerKey);
}
}
好了,action執行完了,還要根據ResultConfig返回到view,也就是在invoke方法中調用executeResult方法。
private void executeResult() throws Exception {
//根據ResultConfig創建Result
result = createResult();

String timerKey = "executeResult: "+getResultCode();
try {
UtilTimerStack.push(timerKey);
if (result != null) {
//這兒正式執行:)
//可以參考Result的實現,如用了比較多的ServletDispatcherResult,ServletActionRedirectResult,ServletRedirectResult
result.execute(this);
} else if (resultCode != null && !Action.NONE.equals(resultCode)) {
throw new ConfigurationException("No result defined for action " + getAction().getClass().getName()
+ " and result " + getResultCode(), proxy.getConfig());
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("No result returned for action "+getAction().getClass().getName()+" at "+proxy.getConfig().getLocation());
}
}
} finally {
UtilTimerStack.pop(timerKey);
}
}
public Result createResult() throws Exception {

if (explicitResult != null) {
Result ret = explicitResult;
explicitResult = null;;
return ret;
}
ActionConfig config = proxy.getConfig();
Map results = config.getResults();

ResultConfig resultConfig = null;

synchronized (config) {
try {
//根據result名稱獲得ResultConfig,resultCode就是result的name
resultConfig = (ResultConfig) results.get(resultCode);
} catch (NullPointerException e) {
}
if (resultConfig == null) {
//如果找不到對應name的ResultConfig,則使用name爲*的Result
resultConfig = (ResultConfig) results.get("*");
}
}

if (resultConfig != null) {
try {
//參照StrutsObjectFactory的代碼
Result result = objectFactory.buildResult(resultConfig, invocationContext.getContextMap());
return result;
} catch (Exception e) {
LOG.error("There was an exception while instantiating the result of type " + resultConfig.getClassName(), e);
throw new XWorkException(e, resultConfig);
}
} else if (resultCode != null && !Action.NONE.equals(resultCode) && unknownHandler != null) {
return unknownHandler.handleUnknownResult(invocationContext, proxy.getActionName(), proxy.getConfig(), resultCode);
}
return null;
}

//StrutsObjectFactory
public Result buildResult(ResultConfig resultConfig, Map extraContext) throws Exception {
String resultClassName = resultConfig.getClassName();
if (resultClassName == null)
return null;
//創建Result,因爲Result是有狀態的,所以每次請求都新建一個
Object result = buildBean(resultClassName, extraContext);
reflectionProvider.setProperties(resultConfig.getParams(), result, extraContext);

if (result instanceof Result)
return (Result) result;
throw new ConfigurationException(result.getClass().getName() + " does not implement Result.");
}


最後的時序圖我拷貝開頭url裏那位作者的圖吧。

本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/myyate/archive/2009/01/12/3759366.aspx
發佈了36 篇原創文章 · 獲贊 0 · 訪問量 1341
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章