淺談:深入理解struts2的流程已經spring和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的整合,把老師上課講的內容總結了一些,希望對求知的人有用。第一次寫博客,寫的不好,請大家見諒

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM