第一步:在tomcat啟動的時候 1、在tomcat啟動的時候,首先會載入struts2的核心過濾器StrutsPrepareAndExecuteFilter 我們打開源代碼,進入核心過濾器 在核心過濾器裡面有init()方法,用於在啟動tomcat的時候初始化struts2用的 首先我們去看一下如 ...
第一步:在tomcat啟動的時候
1、在tomcat啟動的時候,首先會載入struts2的核心過濾器StrutsPrepareAndExecuteFilter
<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>
我們打開源代碼,進入核心過濾器
在核心過濾器裡面有init()方法,用於在啟動tomcat的時候初始化struts2用的
public void init(FilterConfig filterConfig) throws ServletException { InitOperations init = new InitOperations(); Dispatcher dispatcher = null; try { FilterHostConfig config = new FilterHostConfig(filterConfig); init.initLogging(config); dispatcher = init.initDispatcher(config);//用於載入配置文件 init.initStaticContentLoader(config, dispatcher);//用於靜態註入 prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher); execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher); this.excludedPatterns = init.buildExcludedPatternsList(dispatcher); postInit(dispatcher, filterConfig); } finally { if (dispatcher != null) { dispatcher.cleanUpAfterInit(); } init.cleanup(); } }
首先我們去看一下如何去載入配置文件,打開下麵方法的源代碼
dispatcher = init.initDispatcher(config);//用於載入配置文件
就會進入initDispatcher方法,在打開註釋對應的源代碼
public Dispatcher initDispatcher( HostConfig filterConfig ) { Dispatcher dispatcher = createDispatcher(filterConfig); dispatcher.init();//打開他的源代碼 return dispatcher; }
然後你就會發現,在這個init方法中
public void init() { if (configurationManager == null) { configurationManager = createConfigurationManager(DefaultBeanSelectionProvider.DEFAULT_BEAN_NAME); } try {
//有興趣的朋友可以自己再去看更深層次的源代碼,這裡就不深究了 init_FileManager(); init_DefaultProperties(); // [1]//載入struts.properties配置文件 init_TraditionalXmlConfigurations(); // [2]//按照順序載入下麵三個配置文件struts-default.xml(一個),struts-plugin.xml(可能有多個),struts.xml(一個) init_LegacyStrutsProperties(); // [3] init_CustomConfigurationProviders(); // [5] init_FilterInitParameters() ; // [6] init_AliasStandardObjects() ; // [7] Container container = init_PreloadConfiguration(); container.inject(this); init_CheckWebLogicWorkaround(container); if (!dispatcherListeners.isEmpty()) { for (DispatcherListener l : dispatcherListeners) { l.dispatcherInitialized(this); } } } catch (Exception ex) { if (LOG.isErrorEnabled()) LOG.error("Dispatcher initialization failed", ex); throw new StrutsException(ex); } }
看完載入配置文件以後,在回到我們的StrutsPrepareAndExecuteFilter核心過濾器,進入下麵方法的源代碼
public void init(FilterConfig filterConfig) throws ServletException { InitOperations init = new InitOperations(); Dispatcher dispatcher = null; try { FilterHostConfig config = new FilterHostConfig(filterConfig); init.initLogging(config); init.initStaticContentLoader(config, dispatcher);//用於靜態註入 }
這個方法是用來靜態註入
靜態註入:載入struts-defalut.xml裡面的bean屬性的java類,把這些類載入進入struts2
就是下麵這些內容(部分)
<struts> <bean class="com.opensymphony.xwork2.ObjectFactory" name="struts"/> <bean type="com.opensymphony.xwork2.factory.ResultFactory" name="struts" class="org.apache.struts2.factory.StrutsResultFactory" /> <bean type="com.opensymphony.xwork2.factory.ActionFactory" name="struts" class="com.opensymphony.xwork2.factory.DefaultActionFactory"/> <bean type="com.opensymphony.xwork2.factory.ConverterFactory" name="struts" class="com.opensymphony.xwork2.factory.DefaultConverterFactory" /> <bean type="com.opensymphony.xwork2.factory.InterceptorFactory" name="struts" class="com.opensymphony.xwork2.factory.DefaultInterceptorFactory" /> <bean type="com.opensymphony.xwork2.factory.ValidatorFactory" name="struts" class="com.opensymphony.xwork2.factory.DefaultValidatorFactory" /> <bean type="com.opensymphony.xwork2.FileManager" class="com.opensymphony.xwork2.util.fs.DefaultFileManager" name="system" scope="singleton"/> <bean type="com.opensymphony.xwork2.FileManagerFactory" class="com.opensymphony.xwork2.util.fs.DefaultFileManagerFactory" name="struts" scope="singleton"/> ...................................
經過配置文件的載入和靜態註入,struts2容器基本上就啟動了
在請求一個url的時候
回到我們的過濾器,在請求url的時候,struts2首先會執行doFilter(ServletRequest, ServletResponse, FilterChain)方法
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; try { if (excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) { chain.doFilter(request, response); } else { prepare.setEncodingAndLocale(request, response);
//首先打開這個方法的源代碼 prepare.createActionContext(request, response);//創建actionContext prepare.assignDispatcherToThread(); request = prepare.wrapRequest(request); ActionMapping mapping = prepare.findActionMapping(request, response, true); if (mapping == null) { boolean handled = execute.executeStaticResourceRequest(request, response); if (!handled) { chain.doFilter(request, response); } } else { //然後打開這個方法的源代碼 execute.executeAction(request, response, mapping);//創建代理對象(代理對象下麵我們做簡單的說明) } } } finally { prepare.cleanupRequest(request); } }
在訪問action之前,會先創建actionContext對象
public ActionContext createActionContext(HttpServletRequest request, HttpServletResponse response) { ActionContext ctx; Integer counter = 1; Integer oldCounter = (Integer) request.getAttribute(CLEANUP_RECURSION_COUNTER); if (oldCounter != null) { counter = oldCounter + 1; } //在進入getContext()的源代碼 ActionContext oldContext = ActionContext.getContext();
if (oldContext != null) {
// detected existing context, so we are probably in a forward
ctx = new ActionContext(new HashMap<String, Object>(oldContext.getContextMap()));
} else {
//創建值棧
ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
stack.getContext().putAll(dispatcher.createContextMap(request, response, null, servletContext));
ctx = new ActionContext(stack.getContext());
}
request.setAttribute(CLEANUP_RECURSION_COUNTER, counter);
ActionContext.setContext(ctx);
return ctx;
public static ActionContext getContext() { //在進get()的源代碼 return actionContext.get(); }
public T get() { Thread t = Thread.currentThread();//獲取當前線程 ThreadLocalMap map = getMap(t);//從當前線程中獲取 if (map != null) {//如果當前線程中不存在,就創建,並且放入當前線程中 ThreadLocalMap.Entry e = map.getEntry(this);//到這裡說明瞭actionContext存放在當前線程中,所以裡面的數據是線程安全的 if (e != null) return (T)e.value; } return setInitialValue(); }
通過上述的源代碼分析,就可以看出struts2是如何創建actionContext的,並且在創建actionContext之前,值棧就已經創建好了,而且值棧裡面map和actionContext裡面的
map是一樣的。
在看完了瞭如果創建actionContext以後,我們就應該去看如何去創建action代理對象了。創建action對象的方法有很多,一種是利用struts2本身的反射機制,通過ObjectFactory來創建action對象。第二個把創建對象委托給其他容器,例如spring。下麵來說一下使用struts2本身反射機制來創建對象的過程
首先說一下struts2本身來創建action對象,使用代理的方法來生成action代理對象。這裡的action是代理對象
在struts2中,攔截器成為aop的切麵,而我們自己寫的action裡面的方法是目標方法(這裡設計面向切麵編程aop的思想,在這裡就不在多敘述)
在struts2中,有一個核心類,為ObjectFactory,這個類負責所有struts2類的創建,我們可以看一下他的方法體系
這裡面有buildAction(創建action對象),buildResult(創建結果集對象)等一系列創建struts2所需要對象的方法
也就是說,如果要使用其他容器來創建action,必須重新繼承ObjectFactory,然後重新buildAction等方法。
首先我們打開executeAction這個方法
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { ....................................................................
//打開executeAction方法的源代碼 execute.executeAction(request, response, mapping); .................................................................... }
然後進入下麵代碼
public void executeAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws ServletException { //在打開這個方法的源代碼 dispatcher.serviceAction(request, response, servletContext, mapping); }
public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context, ActionMapping mapping) throws ServletException { ................................................................. try { UtilTimerStack.push(timerKey); String namespace = mapping.getNamespace(); String name = mapping.getName(); String method = mapping.getMethod(); Configuration config = configurationManager.getConfiguration(); //獲取action代理對象 ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy( namespace, name, method, extraContext, true, false); 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 {
//打開execute()方法的源代碼,要是DefaultActionProxy這個類下麵的這個方法 proxy.execute(); } ................................................................. }
public String execute() throws Exception { ActionContext nestedContext = ActionContext.getContext(); ActionContext.setContext(invocation.getInvocationContext()); String retCode = null; String profileKey = "execute: "; try { UtilTimerStack.push(profileKey); //進行invoke()源代碼,invoke方法是DefaultActionInvocation類下麵的 retCode = invocation.invoke();/ } finally { if (cleanupContext) { ActionContext.setContext(nestedContext); } UtilTimerStack.pop(profileKey); } return retCode; }
invoke方法就是攔截器struts2的關鍵方法,跟著註釋走,可以看到是先執行攔截器,在執行action裡面的方法,在執行結果集對象
public String invoke() throws Exception { String profileKey = "invoke: "; try { UtilTimerStack.push(profileKey); if (executed) { throw new IllegalStateException("Action has already executed"); } //執行各種攔截器 if (interceptors.hasNext()) { final InterceptorMapping interceptor = interceptors.next(); String interceptorMsg = "interceptor: " + interceptor.getName(); UtilTimerStack.push(interceptorMsg); try { resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this); } finally { UtilTimerStack.pop(interceptorMsg); } } else { resultCode = invokeActionOnly();//執行action裡面的方法 } // this is needed because the result will be executed, then control will return to the Interceptor, which will // return above and flow through again if (!executed) { if (preResultListeners != null) { for (Object preResultListener : preResultListeners) { PreResultListener listener = (PreResultListener) preResultListener; 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); } }
通過結果集對象返回到頁面,就執行了一次請求的過程。上面介紹的
如果是使用spring容器來作為action的產生,那麼就需要對action裡面ObjectFactory類繼承繼承,然後重寫裡面的方法
我們來看一下首先怎麼覆蓋ObjectFactory類,在上面,我說過,xml文件的載入順序是:struts-default.xml,struts-plugin.xml,struts.xml
ObjectFactory在struts-default.xml預設載入的,查看靜態註入可以發現,ObjectFactory被預設載入,如果想成spring的話,可以新建一個struts-plugin.xml
在裡面把它替換掉
<struts> <bean class="com.opensymphony.xwork2.ObjectFactory" name="struts"/>
下麵把文件替換掉,新建一個struts-plugin.xml,這麼ObjectFactory"載入就由spring產生,我們可以進入StrutsSpringObjectFactory源代碼看看
<struts> <!-- 在struts配置文件中引入spring,並且把由struts2自己產生action的 方法,變成由Spring容器產生,覆蓋本身有struts2本身產生的ObjectFactory,進入class源代碼 --> <bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" /> <!-- Make the Spring object factory the automatic default --> <constant name="struts.objectFactory" value="spring" /> <constant name="struts.class.reloading.watchList" value="" /> <constant name="struts.class.reloading.acceptClasses" value="" /> <constant name="struts.class.reloading.reloadConfig" value="false" /> <package name="spring-default"> <interceptors> <interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/> <interceptor name="sessionAutowiring" class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor"/> </interceptors> </package> </struts>
// 進入 SpringObjectFactory
public class StrutsSpringObjectFactory extends SpringObjectFactory {
private static final Logger LOG = LoggerFactory.getLogger(StrutsSpringObjectFactory.class);
這樣就進入了SpringObjectFactory,實現了ObjectFactory並且重寫了ObjectFactory裡面的一些方法
public class SpringObjectFactory extends ObjectFactory implements ApplicationContextAware { private static final Logger LOG = LoggerFactory.getLogger(SpringObjectFactory.class);
我可可以看一下的他的方法體系
在這些方法中,我們來看一下buildBean方法
public Object buildBean(String beanName, Map<String, Object> extraContext, boolean injectInternal) throws Exception { Object o; if (appContext.containsBean(beanName)) { /* 首先從spring容器中獲取action對象,如果獲取不到 就利用反射機制去獲取action,這裡的反射機制,和struts2本身的反射機制應該差不多 */ o = appContext.getBean(beanName); } else { //利用反射機制,實現創建action Class beanClazz = getClassInstance(beanName); o = buildBean(beanClazz, extraContext); } if (injectInternal) { injectInternalBeans(o); } return o; }
通過spring容器,只是action產生方式和以前不同而已,其餘的步驟和方法都相同。我們就分析到這裡了。大家可以試著跟著我的註釋去找源碼,然後設置斷點,使用debug調試,很輕鬆
就可以得到結果。
我也才剛剛學到struts2和spring的整合,把老師上課講的內容總結了一些,希望對求知的人有用。第一次寫博客,寫的不好,請大家見諒