1. 程式人生 > >Struts2體系結構圖以及詳解

Struts2體系結構圖以及詳解

Strut2的體系結構如圖所示:
這裡寫圖片描述

  • 橙色是Servlet Filters,過濾器鏈,所有的請求都要經過Filter鏈的處理。
  • 淺藍色是Struts Core,Struts2的核心部分,Struts2中已經做好的功能,在實際開發中不需要動它們。
  • 淺綠色是Interceptors,Struts2的攔截器。Struts2提供了很多預設的攔截器,可以完成日常開發的絕大部分工作;當然,也可以自定義攔截器,用來實現具體業務需要的功能。
  • 淺黃色是User Created,由開發人員建立的,包括struts.xml、Action、Template,是每個使用Struts2來進行開發的人員都必須會的。
    各模組說明

首先看看它們各自的功能,跟著圖上的箭頭一個一個來看:

  • FilterDispatcher是整個Struts2的排程中心,根據ActionMapper的結果來決定是否處理請求,如果ActionMapper指出該URL應該被Struts2處理,那麼它將會執行Action處理,並停止過濾器鏈上還沒有執行的過濾器。
  • ActionMapper提供了HTTP請求與action執行之間的對映,簡單點說,ActionMapper會判斷這個請求是否應該被Struts2處理,如果需要Struts2處理,ActionMapper會返回一個物件來描述請求對應的ActionInvocation的資訊。
  • ActionProxy是一個特別的中間層,位於Action和xwork之間,使得我們在將來有機會引入更多的實現方式,比如通過WebService來實現等。
  • ConfigurationManager是xwork配置的管理中心,通俗的講,可以把它看做struts.xml這個配置檔案在記憶體中的對應。
  • struts.xml是Stuts2的應用配置檔案,負責諸如URL與Action之間對映的配置、以及執行後頁面跳轉的Result配置等。
  • ActionInvocation:真正呼叫並執行Action,它擁有一個Action例項和這個Action所依賴的攔截器例項。ActionInvocation會執行這些攔截器、Action以及相應的Result。
  • Interceptor(攔截器):攔截器是一些無狀態的類,攔截器可以自動攔截Action,它們給開發者提供了在Action執行之前或Result執行之後來執行一些功能程式碼的機會。類似於我們熟悉的javax.servlet.Filter。
  • Action:動作類是Struts2中的動作執行單元。用來處理使用者請求,並封裝業務所需要的資料。
  • Result:Result就是不同檢視型別的抽象封裝模型,不同的檢視型別會對應不同的Result實現,Struts2中支援多種檢視型別,比如Jsp,FreeMarker等。
  • Templates:各種檢視型別的頁面模板,比如JSP就是一種模板頁面技術。
  • Tag Subsystem:Struts2的標籤庫,它抽象了三種不同的檢視技術JSP、velocity、freemarker,可以在不同的檢視技術中,幾乎沒有差別的使用這些標籤。

Struts2部分類介紹:
ActionMapper ActionMapper其實是HttpServletRequest和Action呼叫請求的一個對映,它遮蔽了Action對於Request等java Servlet類的依賴。Struts2中它的預設實現類是DefaultActionMapper,ActionMapper很大的用處可以根據自己的需要來設計url格式,它自己也有Restful的實現,具體可以參考文件的docs\actionmapper.html。

ActionProxy&ActionInvocation Action的一個代理,由ActionProxyFactory建立,它本身不包括Action例項,預設實現DefaultActionProxy是由ActionInvocation持有Action例項。ActionProxy作用是如何取得Action,無論是本地還是遠端。而ActionInvocation的作用是如何執行Action,攔截器的功能就是在ActionInvocation中實現的。

ConfigurationProvider&Configuration ConfigurationProvider就是Struts2中配置檔案的解析器,Struts2中的配置檔案主要是尤其實現類XmlConfigurationProvider及其子類StrutsXmlConfigurationProvider來解析

Struts2請求流程:
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。

Struts2部分原始碼閱讀
org.apache.struts2.dispatcher.FilterDispatcher

//建立Dispatcher,此類是一個Delegate,它是真正完成根據url解析,讀取對應Action的地方
public void init(FilterConfig filterConfig) throws ServletException {
    try {
        this.filterConfig = filterConfig;
        initLogging();
        dispatcher = createDispatcher(filterConfig);
        dispatcher.init();
        dispatcher.getContainer().inject(this);
        //讀取初始引數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);
    } finally {
        ActionContext.setContext(null);
    }
}

順著流程我們看Disptcher的init方法。init方法裡就是初始讀取一些配置檔案等,先看init_DefaultProperties,主要是讀取properties配置檔案。

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 = 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方法,這個是讀取struts-default.xml和Struts.xml的方法。

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()方法負責讀取標籤,並將資料儲存在ActionConfig中;addResultTypes()方法負責將標籤轉化為ResultTypeConfig物件;loadInterceptors()方法負責將標籤轉化為InterceptorConfi物件;loadInterceptorStack()方法負責將標籤轉化為InterceptorStackConfig物件;loadInterceptorStacks()方法負責將標籤轉化成InterceptorStackConfig物件。而上面的方法最終會被addPackage()方法呼叫,將所讀取到的資料彙集到PackageConfig物件中。

protected PackageConfig addPackage(Element packageElement) throws ConfigurationException {
    PackageConfig.Builder newPackage = buildPackageContext(packageElement);

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

    addResultTypes(newPackage, packageElement);
    loadInterceptors(newPackage, packageElement);
    loadDefaultInterceptorRef(newPackage, packageElement);
    loadDefaultClassRef(newPackage, packageElement);
    loadGlobalResults(newPackage, packageElement);
    loadGobalExceptionMappings(newPackage, packageElement);
    NodeList actionList = packageElement.getElementsByTagName("action");

    for (int i = 0; i < actionList.getLength(); i++) {
        Element actionElement = (Element) actionList.item(i);
        addAction(actionElement, newPackage);
    }
    loadDefaultActionRef(newPackage, packageElement);
    PackageConfig cfg = newPackage.build();
    configuration.addPackageConfig(cfg.getName(), cfg);
    return cfg;
}

XmlConfigurationProvider的原始碼:

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 ) {
                        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 {
        ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
        ActionContext ctx = new ActionContext(stack.getContext());
        ActionContext.setContext(ctx);

        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 {
                chain.doFilter(request, response);
            }
            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.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, 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 {
            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) {
        sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    } finally {
        UtilTimerStack.pop(timerKey);
    }
}

第一句createContextMap()方法,該方法主要把Application、Session、Request的key value值拷貝到Map中,並放在HashMap

public Map<String,Object> createContextMap(HttpServletRequest request, HttpServletResponse response,
    ActionMapping mapping, ServletContext context) {

    // request map wrapping the http request objects
    Map requestMap = new RequestMap(request);
    // parameters map wrapping the http parameters.  ActionMapping parameters are now handled and applied separately
    Map params = new HashMap(request.getParameterMap());
    // session map wrapping the http session
    Map session = new SessionMap(request);
    // application map wrapping the ServletContext
    Map application = new ApplicationMap(context);
    Map<String,Object> extraContext = createContextMap(requestMap, params, session, application, request, response, context);
    extraContext.put(ServletActionContext.ACTION_MAPPING, mapping);
    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();

    // Setting this so that other classes, like object factories, can use the ActionProxy and other
    // contextual information to operate
    ActionContext actionContext = ActionContext.getContext();

    if(actionContext != null) {
        actionContext.setActionInvocation(this);
    }
    //建立Action,可Struts2裡是每次請求都新建一個Action
    createAction(contextMap);

    if (pushAction) {
        stack.push(action);
        contextMap.put("action", action);
    }

    invocationContext = new ActionContext(contextMap);
    invocationContext.setName(proxy.getActionName());

    // get a new List so we don't get problems with the iterator if someone changes the list
    List interceptorList = new ArrayList(proxy.getConfig().getInterceptors());
    interceptors = interceptorList.iterator();
}

protected void createAction(Map contextMap) {
    // load action
    String timerKey = "actionCreate: "+proxy.getActionName();
    try {
        UtilTimerStack.push(timerKey);
        //這兒預設建立Action是StrutsObjectFactory,實際中我使用的時候都是使用Spring建立的Action,這個時候使用的是SpringObjectFactory
        action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);
    } 
    ...
    } 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();
        }

        // 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) {
           //在Result返回之前呼叫preResultListeners
           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 {
            //獲得需要執行的方法
           method = getAction().getClass().getMethod(methodName, new Class[0]);
        } catch (NoSuchMethodException e) {
            //如果沒有對應的方法,則使用do+Xxxx來再次獲得方法
           try {
                String altMethodName = "do" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
                method = getAction().getClass().getMethod(altMethodName, new Class[0]);
            } catch (NoSuchMethodException e1) {
                // well, give the unknown handler a shot
               if (unknownHandler != null) {
                    try {
                        methodResult = unknownHandler.handleUnknownActionMethod(action, methodName);
                        methodCalled = true;
                    } catch (NoSuchMethodException e2) {
                        // throw the original one
                       throw e;
                    }
                } else {
                    throw e;
                }
            }
        }

        if (!methodCalled) {
            methodResult = method.invoke(action, new Object[0]);
        }
        //根據不同的Result型別返回不同值
        //如輸出流Result
       if (methodResult instanceof Result) {
            this.explicitResult = (Result) methodResult;
            return null;
        } else {
            return (String) methodResult;
        }
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException("The " + methodName + "() is not defined in action " + getAction().getClass() + "");
    } catch (InvocationTargetException e) {
        // We try to return the source exception.
        Throwable t = e.getTargetException();

        if (actionEventListener != null) {
            String result = actionEventListener.handleException(t, getStack());
            if (result != null) {
                return result;
            }
        }
        if (t instanceof Exception) {
            throw(Exception) t;
        } else {
            throw e;
        }
    } 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參見OgnlReflectionProvider;
    //resultConfig.getParams()就是result配置檔案裡所配置的引數<param></param>
    //setProperties方法最終呼叫的是Ognl類的setValue方法
    //這句其實就是把param名值設定到根物件result上
    reflectionProvider.setProperties(resultConfig.getParams(), result, extraContext);
    if (result instanceof Result)
        return (Result) result;
    throw new ConfigurationException(result.getClass().getName() + " does not implement Result.");
}

ActionProxy通過Configuration Manager(struts.xml)詢問框架的配置檔案,找到需要呼叫的Action類.

<?xml version="1.0" encoding="GBK"?>
 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
 <struts>
     <include file="struts-default.xml"/>
     <package name="struts2" extends="struts-default">
         <action name="add" 
             class="edisundong.AddAction" >
             <result>add.jsp</result>
         </action>    
     </package>
 </struts>

如果提交請求的是add.action,那麼找到的Action類就是edisundong.AddAction。
ActionProxy建立一個ActionInvocation的例項,同時ActionInvocation通過代理模式呼叫Action。但在呼叫之前ActionInvocation會根據配置載入Action相關的所有Interceptor。(Interceptor是struts2另一個核心級的概念)

下面我們來看看ActionInvocation是如何工作的:

ActionInvocation 是Xworks 中Action 排程的核心。而對Interceptor 的排程,也正是由ActionInvocation負責。ActionInvocation 是一個介面, 而DefaultActionInvocation 則是Webwork 對ActionInvocation的預設實現。

Interceptor 的排程流程大致如下:
1. ActionInvocation初始化時,根據配置,載入Action相關的所有Interceptor。
2. 通過ActionInvocation.invoke方法呼叫Action實現時,執行Interceptor。

Interceptor將很多功能從我們的Action中獨立出來,大量減少了我們Action的程式碼,獨立出來的行為具有很好的重用性。XWork、WebWork的許多功能都是有Interceptor實現,可以在配置檔案中組裝Action用到的Interceptor,它會按照你指定的順序,在Action執行前後執行。
那麼什麼是攔截器。
攔截器就是AOP(Aspect-Oriented Programming)的一種實現。(AOP是指用於在某個方法或欄位被訪問之前,進行攔截然後在之前或之後加入某些操作。)
攔截器的例子這裡就不展開了。
struts-default.xml檔案摘取的內容:

< interceptor name ="alias" class ="com.opensymphony.xwork2.interceptor.AliasInterceptor" /> 
< interceptor name ="autowiring" class ="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor" /> 
< interceptor name ="chain" class ="com.opensymphony.xwork2.interceptor.ChainingInterceptor" /> 
< interceptor name ="conversionError" class ="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor" /> 
< interceptor name ="createSession" class ="org.apache.struts2.interceptor.CreateSessionInterceptor" /> 
< interceptor name ="debugging" class ="org.apache.struts2.interceptor.debugging.DebuggingInterceptor" /> 
< interceptor name ="external-ref" class ="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor" /> 
< interceptor name ="execAndWait" class ="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor" /> 
< interceptor name ="exception" class ="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor" /> 
< interceptor name ="fileUpload" class ="org.apache.struts2.interceptor.FileUploadInterceptor" /> 
< interceptor name ="i18n" class ="com.opensymphony.xwork2.interceptor.I18nInterceptor" /> 
< interceptor name ="logger" class ="com.opensymphony.xwork2.interceptor.LoggingInterceptor" /> 
< interceptor name ="model-driven" class ="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor" /> 
< interceptor name ="scoped-model-driven" class ="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor" /> 
< interceptor name ="params" class ="com.opensymphony.xwork2.interceptor.ParametersInterceptor" /> 
< interceptor name ="prepare" class ="com.opensymphony.xwork2.interceptor.PrepareInterceptor" /> 
< interceptor name ="static-params" class ="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor" /> 
< interceptor name ="scope" class ="org.apache.struts2.interceptor.ScopeInterceptor" /> 
< interceptor name ="servlet-config" class ="org.apache.struts2.interceptor.ServletConfigInterceptor" /> 
< interceptor name ="sessionAutowiring" class ="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor" /> 
< interceptor name ="timer" class ="com.opensymphony.xwork2.interceptor.TimerInterceptor" /> 
< interceptor name ="token" class ="org.apache.struts2.interceptor.TokenInterceptor" /> 
< interceptor name ="token-session" class ="org.apache.struts2.interceptor.TokenSessionStoreInterceptor" /> 
< interceptor name ="validation" class ="com.opensymphony.xwork2.validator.ValidationInterceptor" /> 
< interceptor name ="workflow" class ="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor" /> 
< interceptor name ="store" class ="org.apache.struts2.interceptor.MessageStoreInterceptor" /> 
< interceptor name ="checkbox" class ="org.apache.struts2.interceptor.CheckboxInterceptor" /> 
< interceptor name ="profiling" class ="org.apache.struts2.interceptor.ProfilingActivationInterceptor" /> 
public class TestOgnl {

     private User user;
     private Map context;

     @Before
     public void setUp() throws Exception {

     }

     @Test
     public void ognlGetValue() throws Exception {
     reset();
     Assert.assertEquals("myyate", Ognl.getValue("name", user));
     Assert.assertEquals("cares", Ognl.getValue("dept.name", user));
     Assert.assertEquals("myyate", Ognl.getValue("name", context, user));
     Assert.assertEquals("contextmap", Ognl.getValue("#name", context, user));
     Assert.assertEquals("parker", Ognl.getValue("#pen", context, user));
     }

     @Test
     public void ognlSetValue() throws Exception {
     reset();
     Ognl.setValue("name", user, "myyateC");
     Assert.assertEquals("myyateC", Ognl.getValue("name", user));

     Ognl.setValue("dept.name", user, "caresC");
     Assert.assertEquals("caresC", Ognl.getValue("dept.name", user));

     Assert.assertEquals("contextmap", Ognl.getValue("#name", context, user));
     Ognl.setValue("#name", context, user, "contextmapC");
     Assert.assertEquals("contextmapC", Ognl.getValue("#name", context, user));

     Assert.assertEquals("parker", Ognl.getValue("#pen", context, user));
     Ognl.setValue("#name", context, user, "parkerC");
     Assert.assertEquals("parkerC", Ognl.getValue("#name", context, user));
     }

     public static void main(String[] args) throws Exception {
     JUnitCore.runClasses(TestOgnl.class);
     }

     private void reset() {
     user = new User("myyate", new Dept("cares"));
     context = new OgnlContext();
     context.put("pen", "parker");
     context.put("name", "contextmap");
     }
 }

class User {
     public User(String name, Dept dept) {
     this.name = name;
     this.dept = dept;
     }
     String name;
     private Dept dept;
     public Dept getDept() {
         return dept;
     }
     public String getName() {
         return name;
     }
     public void setDept(Dept dept) {
         this.dept = dept;
     }
     public void setName(String name) {
         this.name = name;
     }
 }

class Dept {
     public Dept(String name) {
     this.name = name;
     }
     private String name;
     public String getName() {
         return name;
     }
     public void setName(String name) {
         this.name = name;
     }
}