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" /> 

最后补充一下,Struts2的查找值和设置值都是使用Ognl来实现的。关于Ognl的介绍可以到其官方网站查看http://www.ognl.org/,我在网上也找到另外一篇http://www.javaeye.com/topic/254684http://www.javaeye.com/topic/223612。完了来看下面这段小测试程序(其它的Ognl的测试可以自己添加)。

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;
     }
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐