淺談:深入理解struts2的流程已經spring和struts2的整合

来源:http://www.cnblogs.com/yghjava/archive/2016/07/26/5709321.html
-Advertisement-
Play Games

第一步:在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的整合,把老師上課講的內容總結了一些,希望對求知的人有用。第一次寫博客,寫的不好,請大家見諒

 

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • R語言中的機器學習程式包主要如下所示: ...
  • learn python3   這是我初學Python時寫的一套Python基礎示常式序.主要基於廖雪峰老師的Python3教程和<<深入理解Python>>. 感謝! 下麵是這些示常式序的目錄總結:  Chapter1:容器/集合/C ...
  • @(MyBatis)[Cache] MyBatis源碼分析——Cache構建以及應用 SqlSession使用緩存流程 如果開啟了二級緩存,而Executor會使用CachingExecutor來裝飾,添加緩存功能,該CachingExecutor會從MappedStatement中獲取對應的Cac ...
  • 當我們享受著jdk帶來的便利時同樣承受它帶來的不幸惡果。通過分析Hashtable就知道,synchronized是針對整張Hash表的,即每次鎖住整張表讓線程獨占,安全的背後是巨大的浪費,而現在的解決方案 ConcurrentHashMap。 ConcurrentHashMap和Hashtable ...
  • 正好需要,在網上找了好久,記錄一下 ...
  • 一、概念 1、定義 反應堆模式是一種對象行為類的設計模式,對同步事件分揀和派發。它是處理併發I/O比較常見的一種模式,用於同步I/O。 其中心思想是將所有要處理的I/O事件註冊到一個中心I/O多路復用器上,同時主線程阻塞在多路復用器上;一旦有I/O事件到來或者是準備就緒,多路復用器返回並將相應的I/ ...
  • 畢業到轉行以來有一年時間了,成為一名程式猿也有大半年了,之前在新浪上隨便寫寫簡單的學習過程,感覺不夠像那麼回事,現在接觸前端也有一段時間了,也做過幾個項目,認識到可以拓展的實在太多了,希望從這裡起步,踏踏實實,記錄好點點滴滴。 HHL Gulp使用步驟: 1 安裝node(npm),全局安裝,我使用 ...
  • 一、概述 工廠方法模式定義了一個創建對象的介面,但由子類決定要實例化的類是哪一個。工廠方法讓類把實例化推遲到子類。 二、解決問題 通常我們需要一個對象的時候,會想到使用new來創建對象 Tea tea = new MilkTea(); //使用了介面,代碼更有彈性,體現設計原則“對介面編程,而不是對 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...