查找靜態資源的源代碼如清單14:
代碼清單14:FilterDispatcher.findStaticResource()方法
protected void findStaticResource(String name, HttpServletRequest request, HttpServletResponse response) throws IOException {
if (!name.endsWith(".class")) {//忽略class文件
//遍歷packages參數
for (String pathPrefix : pathPrefixes) {
InputStream is = findInputStream(name, pathPrefix);//讀取請求文件流
if (is != null) {
……(省略部分代碼)
// set the content-type header
String contentType = getContentType(name);//讀取內容類型
if (contentType != null) {
response.setContentType(contentType);//重新設置內容類型
}
……(省略部分代碼)
try {
//將讀取到的文件流以每次複製4096個字節的方式循環輸出
copy(is, response.getOutputStream());
} finally {
is.close();
}
return;
}
}
}
}
如果用戶請求的資源不是以/struts開頭——可能是.jsp文件,也可能是.html文件,則通過過濾器鏈繼續往下傳送,直到到達請求的資源爲止。
如果getMapping()方法返回有效的ActionMapping對象,則被認爲正在請求某個Action,將調用Dispatcher.serviceAction(request, response, servletContext, mapping)方法,該方法是處理Action的關鍵所在。上述過程的源代碼如清單15所示。
代碼清單15:FilterDispatcher.doFilter()方法
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);
request = prepareDispatcherAndWrapRequest(request, response);//重新包裝request
ActionMapping mapping;
try {
mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());//得到存儲Action信息的ActionMapping對象
} catch (Exception ex) {
……(省略部分代碼)
return;
}
if (mapping == null) {//如果mapping爲null,則認爲不是請求Action資源
String resourcePath = RequestUtils.getServletPath(request);
if ("".equals(resourcePath) && null != request.getPathInfo()) {
resourcePath = request.getPathInfo();
}
//如果請求的資源以/struts開頭,則當作靜態資源處理
if (serveStatic && resourcePath.startsWith("/struts")) {
String name = resourcePath.substring("/struts".length());
findStaticResource(name, request, response);
} else {
//否則,過濾器鏈繼續往下傳遞
chain.doFilter(request, response);
}
// The framework did its job here
return;
}
//如果請求的資源是Action,則調用serviceAction方法。
dispatcher.serviceAction(request, response, servletContext, mapping);
} finally {
try {
ActionContextCleanUp.cleanUp(req);
} finally {
UtilTimerStack.pop(timerKey);
}
}
}
這段代碼的活動圖如圖18所示:
(圖18)
在Dispatcher.serviceAction()方法中,先加載Struts2的配置文件,如果沒有人爲配置,則默認加載struts-default.xml、struts-plugin.xml和struts.xml,並且將配置信息保存在形如com.opensymphony.xwork2.config.entities.XxxxConfig的類中。
類com.opensymphony.xwork2.config.providers.XmlConfigurationProvider負責配置文件的讀取和解析, addAction()方法負責讀取<action>標籤,並將數據保存在ActionConfig中;addResultTypes()方法負責將<result-type>標籤轉化爲ResultTypeConfig對象;loadInterceptors()方法負責將<interceptor>標籤轉化爲InterceptorConfi對象;loadInterceptorStack()方法負責將<interceptor-ref>標籤轉化爲InterceptorStackConfig對象;loadInterceptorStacks()方法負責將<interceptor-stack>標籤轉化成InterceptorStackConfig對象。而上面的方法最終會被addPackage()方法調用,將所讀取到的數據彙集到PackageConfig對象中,細節請參考代碼清單16。
代碼清單16:XmlConfigurationProvider.addPackage()方法
protected PackageConfig addPackage(Element packageElement) throws ConfigurationException {
PackageConfig newPackage = buildPackageContext(packageElement);
if (newPackage.isNeedsRefresh()) {
return newPackage;
}
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
loadGlobalExceptionMappings(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);
configuration.addPackageConfig(newPackage.getName(), newPackage);
return newPackage;
}
活動圖如圖19所示:
(圖19)
配置信息加載完成後,創建一個Action的代理對象——ActionProxy引用,實際上對Action的調用正是通過ActionProxy實現的,而ActionProxy又由ActionProxyFactory創建,ActionProxyFactory是創建ActionProxy的工廠。
注:ActionProxy和ActionProxyFactory都是接口,他們的默認實現類分別是DefaultActionProxy和DefaultActionProxyFactory,位於com.opensymphony.xwork2包下。
在這裏,我們絕對有必要介紹一下com.opensymphony.xwork2.DefaultActionInvocation類,該類是對ActionInvocation接口的默認實現,負責Action和截攔器的執行。
在DefaultActionInvocation類中,定義了invoke()方法,該方法實現了截攔器的遞歸調用和執行Action的execute()方法。其中,遞歸調用截攔器的代碼如清單17所示:
代碼清單17:調用截攔器,DefaultActionInvocation.invoke()方法的部分代碼
if (interceptors.hasNext()) {
//從截攔器集合中取出當前的截攔器
final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();
UtilTimerStack.profile("interceptor: "+interceptor.getName(),
new UtilTimerStack.ProfilingBlock<String>() {
public String doProfiling() throws Exception {
//執行截攔器(Interceptor)接口中定義的intercept方法
resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
return null;
}
});
}
從代碼中似乎看不到截攔器的遞歸調用,其實是否遞歸完全取決於程序員對程序的控制,先來看一下Interceptor接口的定義:
代碼清單18:Interceptor.java
public interface Interceptor extends Serializable {
void destroy();
void init();
String intercept(ActionInvocation invocation) throws Exception;
}
所有的截攔器必須實現intercept方法,而該方法的參數恰恰又是ActionInvocation,所以,如果在intercept方法中調用invocation.invoke(),代碼清單17會再次執行,從Action的Intercepor列表中找到下一個截攔器,依此遞歸。下面是一個自定義截攔器示例:
代碼清單19:CustomIntercepter.java
public class CustomIntercepter extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception
{
actionInvocation.invoke();
return "李贊紅";
}
}
截攔器的調用活動圖如圖20所示:
(圖20)
如果截攔器全部執行完畢,則調用invokeActionOnly()方法執行Action,invokeActionOnly()方法基本沒做什麼工作,只調用了invokeAction()方法。
爲了執行Action,必須先創建該對象,該工作在DefaultActionInvocation的構造方法中調用init()方法早早完成。調用過程是:DefaultActionInvocation()->init()->createAction()。創建Action的代碼如下:
代碼清單20:DefaultActionInvocation.createAction()方法
protected void createAction(Map contextMap) {
try {
action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);
} catch (InstantiationException e) {
……異常代碼省略
}
}
Action創建好後,輪到invokeAction()大顯身手了,該方法比較長,但關鍵語句實在很少,用心點看不會很難。
代碼清單20:DefaultActionInvocation.invokeAction()方法
protected String invokeAction(Object action, ActionConfig actionConfig) throws Exception {
//獲取Action中定義的execute()方法名稱,實際上該方法是可以隨便定義的
String methodName = proxy.getMethod();
String timerKey = "invokeAction: "+proxy.getActionName();
try {
UtilTimerStack.push(timerKey);
Method method;
try {
//將方法名轉化成Method對象
method = getAction().getClass().getMethod(methodName, new Class[0]);
} catch (NoSuchMethodException e) {
// hmm -- OK, try doXxx instead
try {
//如果Method出錯,則嘗試在方法名前加do,再轉成Method對象
String altMethodName = "do" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
method = getAction().getClass().getMethod(altMethodName, new Class[0]);
} catch (NoSuchMethodException e1) {
// throw the original one
throw e;
}
}
//執行方法
Object methodResult = method.invoke(action, new Object[0]);
//處理跳轉
if (methodResult instanceof Result) {
this.result = (Result) methodResult;
return null;
} else {
return (String) methodResult;
}
} catch (NoSuchMethodException e) {
……省略異常代碼
} finally {
UtilTimerStack.pop(timerKey);
}
}
剛纔使用了一段插述,我們繼續回到ActionProxy類。
我們說Action的調用是通過ActionProxy實現的,其實就是調用了ActionProxy.execute()方法,而該方法又調用了ActionInvocation.invoke()方法。歸根到底,最後調用的是DefaultActionInvocation.invokeAction()方法。
以下是調用關係圖:
其中:
Ø ActionProxy:管理Action的生命週期,它是設置和執行Action的起始點。
Ø ActionInvocation:在ActionProxy層之下,它表示了Action的執行狀態。它持有Action實例和所有的Interceptor
以下是serviceAction()方法的定義:
代碼清單21: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);
}
}
最後,通過Result完成頁面的跳轉。
3.4 本小節總結
總體來講,Struts2的工作機制比Struts1.x要複雜很多,但我們不得不佩服Struts和WebWork開發小組的功底,代碼如此優雅,甚至能夠感受看到兩個開發小組心神相通的默契。兩個字:佩服。