Struts2源码分析

来源:互联网 发布:exm什么意思网络用语 编辑:程序博客网 时间:2024/06/05 11:13

Struts2架构流程图

Struts2部分类介绍

这部分从Struts2参考文档中翻译就可以了。
ActionMapper
        ActionMapper其实是HttpServletRequest和Action调用请求的一个映射,它屏蔽了Action对于Request等JavaServlet类的依赖。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、客户端发送请求
2、请求先通过ActionContextCleanUp-->FilterDispatcher
3、FilterDispatcher通过ActionMapper来决定这个Request需要调用哪个Action
4、如果ActionMapper决定调用某个Action,FilterDispatcher把请求的处理交给ActionProxy,这儿已经转到它的Delegate--Dispatcher来执行
5、ActionProxy根据ActionMapping和ConfigurationManager找到需要调用的Action类
6、ActionProxy创建一个ActionInvocation的实例
7、ActionInvocation调用真正的Action,当然这涉及到相关拦截器的调用
8、Action执行完毕,ActionInvocation创建Result并返回,当然,如果要在返回之前做些什么,可以实现PreResultListener。添加PreResultListener可以在Interceptor中实现,不知道其它还有什么方式?


Struts2(2.3.4)部分代码阅读

web.xml配置:

自从struts 2.1.3以后,FilterDispatcher已标注为过时改用StrutsPrepareAndExecuteFilter。我们此文将剖析StrutsPrepareAndExecuteFilter,其在工程中作为一个Filter配置在web.xml中,配置如下:

[html] view plain copy
  1. <filter>  
  2.     <filter-name>struts2</filter-name>  
  3.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  4. </filter>  
  5.   
  6. <filter-mapping>  
  7.     <filter-name>struts2</filter-name>  
  8.     <url-pattern>/*</url-pattern>  
  9. </filter-mapping>  

从org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter开始

[java] view plain copy
  1.  public void init(FilterConfig filterConfig) throws ServletException {  
  2.     //创建一个InitOperations初始化操作的对象  
  3.      InitOperations init = new InitOperations();  
  4.      try {  
  5.          //封装filterConfig,其中有个主要方法getInitParameterNames将参数名字以String格式存储在List中  
  6.          FilterHostConfig config = new FilterHostConfig(filterConfig);  
  7.          // 初始化struts内部日志    
  8.          init.initLogging(config);  
  9.          //创建dispatcher对象,并读取配置文件     
  10.          Dispatcher dispatcher = init.initDispatcher(config);  
  11.          init.initStaticContentLoader(config, dispatcher);  
  12.            
  13.          //初始化类属性:prepare 、execute    
  14.          prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);  
  15.          execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);  
  16. this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);  
  17.   
  18. //回调空的postInit方法  
  19.          postInit(dispatcher, filterConfig);  
  20.      } finally {  
  21.          init.cleanup();  
  22.      }  
  23.  }  

首先看下FilterHostConfig ,只有短短的几行代码,getInitParameterNames是这个类的核心,将Filter初始化参数名称有枚举类型转为Iterator。此类的主要作为是对filterConfig 封装,源码如下: 

[java] view plain copy
  1. public class FilterHostConfig implements HostConfig {  
  2.   
  3.     private FilterConfig config;  
  4.     /* 
  5.      * 构造函数 
  6.      */   
  7.     public FilterHostConfig(FilterConfig config) {  
  8.         this.config = config;  
  9.     }  
  10.       
  11.     //根据init-param配置的param-name获取param-value的值  
  12.     public String getInitParameter(String key) {  
  13.         return config.getInitParameter(key);  
  14.     }  
  15.   
  16.     //返回初始化参数名的List  
  17.     public Iterator<String> getInitParameterNames() {  
  18.         return MakeIterator.convert(config.getInitParameterNames());  
  19.     }  
  20.   
  21.     public ServletContext getServletContext() {  
  22.         return config.getServletContext();  
  23.     }  
  24. }  

InitOperations的initDispatcher方法。initDispatcher方法,创建dispatcher对象,并读取配置文件 。

[java] view plain copy
  1. public Dispatcher initDispatcher(HostConfig filterConfig) {  
  2.     // 创建dispatcher对象,将参数传递dispatcher全局变量  
  3.     Dispatcher dispatcher = createDispatcher(filterConfig);  
  4.     // 初始化配置文件/读取配置文件  
  5.     dispatcher.init();  
  6.     return dispatcher;  
  7. }  

InitOperations的createDispatcher方法。创建Dispatcher,会读取 filterConfig中的配置信息。

[java] view plain copy
  1.     /* 
  2.      * 创建Dispatcher,会读取 filterConfig 
  3.      * 中的配置信息,将配置信息解析出来,封装成为一个Map,然后根绝servlet上下文和参数Map构造Dispatcher 
  4.      */  
  5.     private Dispatcher createDispatcher(HostConfig filterConfig) {  
  6.         Map<String, String> params = new HashMap<String, String>();  
  7.         // 获得在web.xml中所有的配置文件,将参数放入params Map集合中  
  8.         for (Iterator e = filterConfig.getInitParameterNames(); e.hasNext();) {  
  9.             String name = (String) e.next();  
  10.             String value = filterConfig.getInitParameter(name);  
  11.             params.put(name, value);  
  12.         }  
  13.         // 创建Dispatcher 对象,将ServletContext(),将参数赋给Dispatcher的全局私有变量中  
  14.         return new Dispatcher(filterConfig.getServletContext(), params);  
  15.     }  

顺着流程我们看Disptcher的init方法。init方法里就是初始读取一些配置文件等,先看init_DefaultProperties,主要是读取properties配置文件。

[java] view plain copy
  1.         public void init() {  
  2.         /* 
  3.          * 如果 configurationManager为空,则创建configurationManager对象, 
  4.          * 在configurationManager构函数 将 BeanSelectionProvider.DEFAULT_BEAN_NAME(常量值struts) 
  5.          * 赋给全局变量protected String defaultFrameworkBeanName; 
  6.          */  
  7.         if (configurationManager == null) {  
  8.             configurationManager = createConfigurationManager(BeanSelectionProvider.DEFAULT_BEAN_NAME);  
  9.         }  
  10.   
  11.         try {  
  12.             //主要是读取properties配置文件  
  13.             init_DefaultProperties(); // [1]  
  14.             //读取struts-default.xml和Struts.xml的方法  
  15.             init_TraditionalXmlConfigurations(); // [2]  
  16.             init_LegacyStrutsProperties(); // [3]  
  17.             /*  
  18.              * init_CustomConfigurationProviders方式初始自定义的Provider, 
  19.              * 配置类全名和实现ConfigurationProvider接口,用逗号隔开即可。 
  20.              */  
  21.             init_CustomConfigurationProviders(); // [5]  
  22.   
  23.             //Filter的初始化参数  
  24.             init_FilterInitParameters() ; // [6]  
  25.             init_AliasStandardObjects() ; // [7]  
  26.   
  27.             Container container = init_PreloadConfiguration();  
  28.             container.inject(this);  
  29.             init_CheckConfigurationReloading(container);  
  30.             init_CheckWebLogicWorkaround(container);  
  31.   
  32.             if (!dispatcherListeners.isEmpty()) {  
  33.                 for (DispatcherListener l : dispatcherListeners) {  
  34.                     l.dispatcherInitialized(this);  
  35.                 }  
  36.             }  
  37.         } catch (Exception ex) {  
  38.             if (LOG.isErrorEnabled())  
  39.                 LOG.error("Dispatcher initialization failed", ex);  
  40.             throw new StrutsException(ex);  
  41.         }  
  42.     }  

init_DefaultProperties方法,初始化default.properties,具体的初始化操作在DefaultPropertiesProvider类中

[java] view plain copy
  1.     private void init_DefaultProperties() {  
  2.         configurationManager.addContainerProvider(new DefaultPropertiesProvider());  
  3.     }  

打开DefaultPropertiesProvider类源码:

[java] view plain copy
  1.     public void register(ContainerBuilder builder, LocatableProperties props)  
  2.             throws ConfigurationException {  
  3.   
  4.         Settings defaultSettings = null;  
  5.         try {  
  6.             // 读取properties属性文件方法  
  7.             defaultSettings = new PropertiesSettings(  
  8.                     "org/apache/struts2/default");  
  9.         } catch (Exception e) {  
  10.             throw new ConfigurationException(  
  11.                     "Could not find or error in org/apache/struts2/default.properties",  
  12.                     e);  
  13.         }  
  14.   
  15.         loadSettings(props, defaultSettings);  
  16.     }  

再来看init_TraditionalXmlConfigurations方法,这个是读取struts-default.xml和Struts.xml的方法。

[java] view plain copy
  1.     //init_TraditionalXmlConfigurations方法,这个是读取struts-default.xml和Struts.xml的方法  
  2.     private void init_TraditionalXmlConfigurations() {  
  3.         /* 
  4.          * 首先读取web.xml中的config初始参数值 
  5.          * 如果没有配置就使用默认的"struts-default.xml,struts-plugin.xml,struts.xml", 
  6.          * 这儿就可以看出为什么默认的配置文件必须取名为这三个名称了 
  7.          * 如果不想使用默认的名称,直接在web.xml中配置config初始参数即可 
  8.          */  
  9.         String configPaths = initParams.get("config");  
  10.         if (configPaths == null) {  
  11.             configPaths = DEFAULT_CONFIGURATION_PATHS;  
  12.         }  
  13.         String[] files = configPaths.split("\\s*[,]\\s*");  
  14.         for (String file : files) {  
  15.             if (file.endsWith(".xml")) {  
  16.                 //依次解析配置文件,xwork.xml单独解析,除xwork.xml外,  
  17.                 //全都调用createStrutsXmlConfigurationProvider()方法,  
  18.                 //StrutsXmlConfigurationProvider进行解析  
  19.                 if ("xwork.xml".equals(file)) {  
  20.                     configurationManager.addContainerProvider(createXmlConfigurationProvider(file, false));  
  21.                 } else {  
  22.                     configurationManager.addContainerProvider(createStrutsXmlConfigurationProvider(file, false, servletContext));  
  23.                 }  
  24.             } else {  
  25.                 throw new IllegalArgumentException("Invalid configuration file name");  
  26.             }  
  27.         }  
  28.     }   

       StrutsXmlConfigurationProvider类继承XmlConfigurationProvider,而XmlConfigurationProvider又实现 ConfigurationProvider接口。类XmlConfigurationProvider负责配置文件的读取和解析,addAction()方法负责读取<action>标签,并将数据保存在ActionConfig 中;addResultTypes()方法负责将<result-type>标签转化为ResultTypeConfig对象;loadInterceptors()方法负责将<interceptor>标签转化为InterceptorConfi对象;loadInterceptorStack()方法负责将<interceptor-ref>标签转化为 InterceptorStackConfig对象;loadInterceptorStacks()方法负责将<interceptor- stack>标签转化成InterceptorStackConfig对象。而上面的方法最终会被addPackage()方法调用,将所读取到的数据汇集到PackageConfig对象中。

[java] view plain copy
  1.      protected PackageConfig addPackage(Element packageElement) throws ConfigurationException {  
  2.         PackageConfig.Builder newPackage = buildPackageContext(packageElement);  
  3.   
  4.         if (newPackage.isNeedsRefresh()) {  
  5.             return newPackage.build();  
  6.         }  
  7.   
  8.         if (LOG.isDebugEnabled()) {  
  9.             LOG.debug("Loaded " + newPackage);  
  10.         }  
  11.   
  12.         // add result types (and default result) to this package  
  13.         addResultTypes(newPackage, packageElement);  
  14.   
  15.         // load the interceptors and interceptor stacks for this package  
  16.         loadInterceptors(newPackage, packageElement);  
  17.   
  18.         // load the default interceptor reference for this package  
  19.         loadDefaultInterceptorRef(newPackage, packageElement);  
  20.   
  21.         // load the default class ref for this package  
  22.         loadDefaultClassRef(newPackage, packageElement);  
  23.   
  24.         // load the global result list for this package  
  25.         loadGlobalResults(newPackage, packageElement);  
  26.   
  27.         // load the global exception handler list for this package  
  28.         loadGobalExceptionMappings(newPackage, packageElement);  
  29.   
  30.         // get actions  
  31.         NodeList actionList = packageElement.getElementsByTagName("action");  
  32.   
  33.         for (int i = 0; i < actionList.getLength(); i++) {  
  34.             Element actionElement = (Element) actionList.item(i);  
  35.             addAction(actionElement, newPackage);  
  36.         }  
  37.   
  38.         // load the default action reference for this package  
  39.         loadDefaultActionRef(newPackage, packageElement);  
  40.   
  41.         PackageConfig cfg = newPackage.build();  
  42.         configuration.addPackageConfig(cfg.getName(), cfg);  
  43.         return cfg;  
  44.     }  
  45.   
  46.     private List<Document> loadConfigurationFiles(String fileName, Element includeElement) {  
  47.         List<Document> docs = new ArrayList<Document>();  
  48.         List<Document> finalDocs = new ArrayList<Document>();  
  49.         if (!includedFileNames.contains(fileName)) {  
  50.             if (LOG.isDebugEnabled()) {  
  51.                 LOG.debug("Loading action configurations from: " + fileName);  
  52.             }  
  53.   
  54.             includedFileNames.add(fileName);  
  55.   
  56.             Iterator<URL> urls = null;  
  57.             InputStream is = null;  
  58.   
  59.             IOException ioException = null;  
  60.             try {  
  61.                 urls = getConfigurationUrls(fileName);  
  62.             } catch (IOException ex) {  
  63.                 ioException = ex;  
  64.             }  
  65.   
  66.             if (urls == null || !urls.hasNext()) {  
  67.                 if (errorIfMissing) {  
  68.                     throw new ConfigurationException("Could not open files of the name " + fileName, ioException);  
  69.                 } else {  
  70.                     if (LOG.isInfoEnabled()) {  
  71.                     LOG.info("Unable to locate configuration files of the name "  
  72.                             + fileName + ", skipping");  
  73.                     }  
  74.                     return docs;  
  75.                 }  
  76.             }  
  77.   
  78.             URL url = null;  
  79.             while (urls.hasNext()) {  
  80.                 try {  
  81.                     url = urls.next();  
  82.                     is = fileManager.loadFile(url);  
  83.   
  84.                     InputSource in = new InputSource(is);  
  85.   
  86.                     in.setSystemId(url.toString());  
  87.   
  88.                     docs.add(DomHelper.parse(in, dtdMappings));  
  89.                 } catch (XWorkException e) {  
  90.                     if (includeElement != null) {  
  91.                         throw new ConfigurationException("Unable to load " + url, e, includeElement);  
  92.                     } else {  
  93.                         throw new ConfigurationException("Unable to load " + url, e);  
  94.                     }  
  95.                 } catch (Exception e) {  
  96.                     final String s = "Caught exception while loading file " + fileName;  
  97.                     throw new ConfigurationException(s, e, includeElement);  
  98.                 } finally {  
  99.                     if (is != null) {  
  100.                         try {  
  101.                             is.close();  
  102.                         } catch (IOException e) {  
  103.                             LOG.error("Unable to close input stream", e);  
  104.                         }  
  105.                     }  
  106.                 }  
  107.             }  
  108.   
  109.             //sort the documents, according to the "order" attribute  
  110.             Collections.sort(docs, new Comparator<Document>() {  
  111.                 public int compare(Document doc1, Document doc2) {  
  112.                     return XmlHelper.getLoadOrder(doc1).compareTo(XmlHelper.getLoadOrder(doc2));  
  113.                 }  
  114.             });  
  115.   
  116.             for (Document doc : docs) {  
  117.                 Element rootElement = doc.getDocumentElement();  
  118.                 NodeList children = rootElement.getChildNodes();  
  119.                 int childSize = children.getLength();  
  120.   
  121.                 for (int i = 0; i < childSize; i++) {  
  122.                     Node childNode = children.item(i);  
  123.   
  124.                     if (childNode instanceof Element) {  
  125.                         Element child = (Element) childNode;  
  126.   
  127.                         final String nodeName = child.getNodeName();  
  128.                         //解析每个action配置是,对于include文件可以使用通配符*来进行配置  
  129.                         //如Struts.xml中可配置成<include file="actions_*.xml"/>  
  130.                         if ("include".equals(nodeName)) {  
  131.                             //获得file属性 例如: <include file="example.xml"/>  
  132.                             String includeFileName = child.getAttribute("file");  
  133.                             if (includeFileName.indexOf('*') != -1) {  
  134.                                 // handleWildCardIncludes(includeFileName, docs, child);  
  135.                                 ClassPathFinder wildcardFinder = new ClassPathFinder();  
  136.                                 wildcardFinder.setPattern(includeFileName);  
  137.                                   
  138.                                 Vector<String> wildcardMatches = wildcardFinder.findMatches();  
  139.                                 for (String match : wildcardMatches) {  
  140.                                     finalDocs.addAll(loadConfigurationFiles(match, child));  
  141.                                 }   
  142.                             } else {  
  143.                                 finalDocs.addAll(loadConfigurationFiles(includeFileName, child));  
  144.                             }  
  145.                         }  
  146.                     }  
  147.                 }  
  148.                 finalDocs.add(doc);  
  149.                 loadedFileUrls.add(url.toString());  
  150.             }  
  151.   
  152.             if (LOG.isDebugEnabled()) {  
  153.                 LOG.debug("Loaded action configuration from: " + fileName);  
  154.             }  
  155.         }  
  156.         return finalDocs;  
  157.     }  

init_CustomConfigurationProviders方式初始自定义的Provider,配置类全名和实现ConfigurationProvider接口,用逗号隔开即可。

[java] view plain copy
  1.     //init_CustomConfigurationProviders方式初始自定义的Provider,配置类全名和实现ConfigurationProvider接口,用逗号隔开即可。  
  2.     private void init_CustomConfigurationProviders() {  
  3.         /* 
  4.          * 首先读取web.xml中的configProviders初始参数值 
  5.          * 如果有配置则去加载。 
  6.          */  
  7.         String configProvs = initParams.get("configProviders");  
  8.         if (configProvs != null) {  
  9.             String[] classes = configProvs.split("\\s*[,]\\s*");  
  10.             for (String cname : classes) {  
  11.                 try {  
  12.                     Class cls = ClassLoaderUtil.loadClass(cname, this.getClass());  
  13.                     ConfigurationProvider prov = (ConfigurationProvider)cls.newInstance();  
  14.                     configurationManager.addContainerProvider(prov);  
  15.                 } catch (InstantiationException e) {  
  16.                     throw new ConfigurationException("Unable to instantiate provider: "+cname, e);  
  17.                 } catch (IllegalAccessException e) {  
  18.                     throw new ConfigurationException("Unable to access provider: "+cname, e);  
  19.                 } catch (ClassNotFoundException e) {  
  20.                     throw new ConfigurationException("Unable to locate provider class: "+cname, e);  
  21.                 }  
  22.             }  
  23.         }  
  24.     }  

现在再回到FilterDispatcher,每次发送一个Request,FilterDispatcher都会调用doFilter方法。doFilter是过滤器的执行方法,它拦截提交的HttpServletRequest请求,HttpServletResponse响应,是strtus2的核心拦截器。

[java] view plain copy
  1.     //每次发送一个Request,StrutsPrepareAndExecuteFilter都会调用doFilter方法  
  2.     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
  3.   
  4.         HttpServletRequest request = (HttpServletRequest) req;  
  5.         HttpServletResponse response = (HttpServletResponse) res;  
  6.   
  7.         try {  
  8.             //设置编码和国际化    
  9.             prepare.setEncodingAndLocale(request, response);  
  10.             //ActionContext创建  
  11.             prepare.createActionContext(request, response);  
  12.             prepare.assignDispatcherToThread();  
  13.             if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {  
  14.                 chain.doFilter(request, response);  
  15.             } else {  
  16.                 request = prepare.wrapRequest(request);  
  17.                 ActionMapping mapping = prepare.findActionMapping(request, response, true);  
  18.                 //如果找不到对应的action配置  
  19.                 if (mapping == null) {  
  20.                     /* 
  21.                      * 就是如果path是以“/struts”开头,则到初始参数packages配置的包路径去查找对应的静态资源并输出到页面流中, 
  22.                      * 当然.class文件除外。如果再没有则跳转到404 
  23.                      */  
  24.                     boolean handled = execute.executeStaticResourceRequest(request, response);  
  25.                     if (!handled) {  
  26.                         chain.doFilter(request, response);  
  27.                     }  
  28.                 } else {  
  29.                     /* 
  30.                      * 找到对应action配置文件后,调用ExecuteOperations类中executeAction, 
  31.                      * 开始谳用Action的方法。 
  32.                      */  
  33.                     execute.executeAction(request, response, mapping);  
  34.                 }  
  35.             }  
  36.         } finally {  
  37.             prepare.cleanupRequest(request);  
  38.         }  
  39.     }  
setEncodingAndLocale调用了dispatcher方法的prepare方法。

[java] view plain copy
  1.      //setEncodingAndLocale调用了dispatcher方法的prepare方法  
  2.     public void setEncodingAndLocale(HttpServletRequest request, HttpServletResponse response) {  
  3.         dispatcher.prepare(request, response);  
  4.     }  

prepare方法,这个方法很简单只是设置了encoding 、locale ,做的只是一些辅助的工作。

[java] view plain copy
  1.     public void prepare(HttpServletRequest request, HttpServletResponse response) {  
  2.         String encoding = null;  
  3.         if (defaultEncoding != null) {  
  4.             encoding = defaultEncoding;  
  5.         }  
  6.         // check for Ajax request to use UTF-8 encoding strictly http://www.w3.org/TR/XMLHttpRequest/#the-send-method  
  7.         if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {  
  8.             encoding = "utf-8";  
  9.         }  
  10.   
  11.         Locale locale = null;  
  12.         if (defaultLocale != null) {  
  13.             locale = LocalizedTextUtil.localeFromString(defaultLocale, request.getLocale());  
  14.         }  
  15.         //设置encoding编号为UTF-8  
  16.         if (encoding != null) {  
  17.             applyEncoding(request, encoding);  
  18.         }  
  19.   
  20.         if (locale != null) {  
  21.             response.setLocale(locale);  
  22.         }  
  23.   
  24.         if (paramsWorkaroundEnabled) {  
  25.             request.getParameter("foo"); // simply read any parameter (existing or not) to "prime" the request  
  26.         }  
  27.     }  

ActionContext是一个容器,这个容易主要存储request、session、application、parameters等相关信息.ActionContext是一个线程的本地变量,这意味着不同的action之间不会共享ActionContext,所以也不用考虑线程安全问题。其实质是一个Map,key是标示request、session、……的字符串,值是其对应的对象

[java] view plain copy
  1.     public class ActionContext implements Serializable {  
  2.         static ThreadLocal actionContext = new ThreadLocal();  
  3.         Map<String, Object> context;  
  4.         //省略其它的代码……  
  5.     }  
ActionContext上下文的创建

[java] view plain copy
  1.     //创建ActionContext,初始化thread local   
  2.     public ActionContext createActionContext(HttpServletRequest request, HttpServletResponse response) {  
  3.         ActionContext ctx;  
  4.         Integer counter = 1;  
  5.         Integer oldCounter = (Integer) request.getAttribute(CLEANUP_RECURSION_COUNTER);  
  6.         if (oldCounter != null) {  
  7.             counter = oldCounter + 1;  
  8.         }  
  9.           
  10.         //从ThreadLocal中获取此ActionContext变量  
  11.         ActionContext oldContext = ActionContext.getContext();  
  12.         if (oldContext != null) {  
  13.             // detected existing context, so we are probably in a forward  
  14.             ctx = new ActionContext(new HashMap<String, Object>(oldContext.getContextMap()));  
  15.         } else {  
  16.             ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();  
  17.             stack.getContext().putAll(dispatcher.createContextMap(request, response, null, servletContext));  
  18.             //stack.getContext()返回的是一个Map<String,Object>,根据此Map构造一个ActionContext    
  19.             ctx = new ActionContext(stack.getContext());  
  20.         }  
  21.         request.setAttribute(CLEANUP_RECURSION_COUNTER, counter);  
  22.           
  23.         //将ActionContext保存ThreadLocal    
  24.         ActionContext.setContext(ctx);  
  25.         return ctx;  
  26.     }  

上面代码中dispatcher.createContextMap,如何封装相关参数:

[java] view plain copy
  1.     public Map<String,Object> createContextMap(HttpServletRequest request, HttpServletResponse response,  
  2.             ActionMapping mapping, ServletContext context) {  
  3.   
  4.         /* 
  5.          * 对request包装requestMap 
  6.          * 对params包装 params 
  7.          * 对session包装 session 
  8.          * 对context包装application 
  9.          * 实际都是Map 
  10.          */  
  11.         // request map wrapping the http request objects  
  12.         Map requestMap = new RequestMap(request);  
  13.   
  14.         // parameters map wrapping the http parameters.  ActionMapping parameters are now handled and applied separately  
  15.         Map params = new HashMap(request.getParameterMap());  
  16.   
  17.         // session map wrapping the http session  
  18.         Map session = new SessionMap(request);  
  19.   
  20.         // application map wrapping the ServletContext  
  21.         Map application = new ApplicationMap(context);  
  22.   
  23.         //requestMap、params、session等Map封装成为一个上下文Map,逐个调用了map.put(Map p).   
  24.         Map<String,Object> extraContext = createContextMap(requestMap, params, session, application, request, response, context);  
  25.   
  26.         if (mapping != null) {  
  27.             extraContext.put(ServletActionContext.ACTION_MAPPING, mapping);  
  28.         }  
  29.         //返回一个封装对象的Map——extraContext  
  30.         return extraContext;  
  31.     }  

简单看下RequestMap,其他的省略。RequestMap类实现了抽象Map,故其本身是一个Map,主要方法实现:

[java] view plain copy
  1.     //map的get实现    
  2.     public Object get(Object key) {  
  3.         return request.getAttribute(key.toString());  
  4.     }  
  5.       
  6.         //map的put实现    
  7.     public Object put(Object key, Object value) {  
  8.         Object oldValue = get(key);  
  9.         entries = null;  
  10.         request.setAttribute(key.toString(), value);  
  11.         return oldValue;  
  12.     }  
Dispatcher类的serviceAction方法:

[java] view plain copy
  1.     //map的get实现    
  2.     public Object get(Object key) {  
  3.         return request.getAttribute(key.toString());  
  4.     }  
  5.       
  6.         //map的put实现    
  7.     public Object put(Object key, Object value) {  
  8.         Object oldValue = get(key);  
  9.         entries = null;  
  10.         request.setAttribute(key.toString(), value);  
  11.         return oldValue;  
  12.     }  
执行Action,抛出ServletException异常:

[java] view plain copy
  1.     public void executeAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws ServletException {  
  2.         dispatcher.serviceAction(request, response, servletContext, mapping);  
  3.     }  
继续查看,dispatcher.serviceAction方法:

[java] view plain copy
  1.     public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,  
  2.                               ActionMapping mapping) throws ServletException {  
  3.         /* 
  4.          * createContextMap()方法,该方法主要把Application、Session、Request的key value值拷贝到Map中, 
  5.          * 并放在HashMap<String,Object>中,可以参见createContextMap方法: 
  6.          */  
  7.         Map<String, Object> extraContext = createContextMap(request, response, mapping, context);  
  8.   
  9.         // If there was a previous value stack, then create a new copy and pass it in to be used by the new Action  
  10.         //从request范围中通过struts.valueStack获得 stack对象  
  11.         ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);  
  12.         boolean nullStack = stack == null;  
  13.         if (nullStack) {  
  14.             ActionContext ctx = ActionContext.getContext();  
  15.             if (ctx != null) {  
  16.                 stack = ctx.getValueStack();  
  17.             }  
  18.         }  
  19.         if (stack != null) {  
  20.             extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));  
  21.         }  
  22.   
  23.         String timerKey = "Handling request from Dispatcher";  
  24.         try {  
  25.             UtilTimerStack.push(timerKey);  
  26.             //获得命名空间  
  27.             String namespace = mapping.getNamespace();  
  28.             //获得action配置的名称  
  29.             String name = mapping.getName();  
  30.             //获得action配置的方法,即method属性  
  31.             String method = mapping.getMethod();  
  32.   
  33.             Configuration config = configurationManager.getConfiguration();  
  34.             /* 
  35.              * 从容器中获得ActionProxyFactory代理工厂 
  36.              * ActionProxyFactory,它是创建ActionProxy来执行一个特定的命名空间和动作的名称是由调度使用XWork的切入点。 
  37.              * 由ActionProxyFactory创建ActionProxy 
  38.              */  
  39.             ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(  
  40.                     namespace, name, method, extraContext, truefalse);  
  41.   
  42.             request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());  
  43.   
  44.             // if the ActionMapping says to go straight to a result, do it!  
  45.             //执行execute方法,并转向结果   
  46.             if (mapping.getResult() != null) {  
  47.                 Result result = mapping.getResult();  
  48.                 result.execute(proxy.getInvocation());  
  49.             } else {  
  50.                 proxy.execute();  
  51.             }  
  52.   
  53.             // If there was a previous value stack then set it back onto the request  
  54.             if (!nullStack) {  
  55.                 request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);  
  56.             }  
  57.         } catch (ConfigurationException e) {  
  58.             // WW-2874 Only log error if in devMode  
  59.             if(devMode) {  
  60.                 String reqStr = request.getRequestURI();  
  61.                 if (request.getQueryString() != null) {  
  62.                     reqStr = reqStr + "?" + request.getQueryString();  
  63.                 }  
  64.                 LOG.error("Could not find action or result\n" + reqStr, e);  
  65.             }  
  66.             else {  
  67.                     if (LOG.isWarnEnabled()) {  
  68.                 LOG.warn("Could not find action or result", e);  
  69.                     }  
  70.             }  
  71.             sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);  
  72.         } catch (Exception e) {  
  73.             sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);  
  74.         } finally {  
  75.             UtilTimerStack.pop(timerKey);  
  76.         }  
  77.     }  

在上面的源代码中,dispatcher.serviceAction方法里面,调用了createActionProxy方法:

[java] view plain copy
  1.             ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(  
  2.                     namespace, name, method, extraContext, truefalse);  

创建ActionPorxy对象,并调用调用proxy的prepare方法:

[java] view plain copy
  1.     public ActionProxy createActionProxy(String namespace, String actionName, String methodName, Map<String, Object> extraContext, boolean executeResult, boolean cleanupContext) {  
  2.         ActionInvocation inv = new DefaultActionInvocation(extraContext, true);  
  3.         container.inject(inv);  
  4.         return createActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);  
  5.     }  
  6.   
  7.     public ActionProxy createActionProxy(ActionInvocation inv, String namespace, String actionName, String methodName, boolean executeResult, boolean cleanupContext) {  
  8.         DefaultActionProxy proxy = new DefaultActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);  
  9.         container.inject(proxy);  
  10.         //调用proxy的prepare()方法  
  11.         proxy.prepare();  
  12.         return proxy;  
  13.     }  
  14.   
  15.     protected void prepare() {  
  16.         String profileKey = "create DefaultActionProxy: ";  
  17.         try {  
  18.             UtilTimerStack.push(profileKey);  
  19.             config = configuration.getRuntimeConfiguration().getActionConfig(namespace, actionName);  
  20.   
  21.             if (config == null && unknownHandlerManager.hasUnknownHandlers()) {  
  22.                 config = unknownHandlerManager.handleUnknownAction(namespace, actionName);  
  23.             }  
  24.             if (config == null) {  
  25.                 throw new ConfigurationException(getErrorMessage());  
  26.             }  
  27.   
  28.             resolveMethod();  
  29.   
  30.             if (!config.isAllowedMethod(method)) {  
  31.                 throw new ConfigurationException("Invalid method: " + method + " for action " + actionName);  
  32.             }  
  33.             //invocation调用初始化的方法  
  34.             invocation.init(this);  
  35.   
  36.         } finally {  
  37.             UtilTimerStack.pop(profileKey);  
  38.         }  
  39.     }  
       后面才是最主要的--ActionProxy,ActionInvocation。ActionProxy是Action的一个代理类,也就是说Action的调用是通过ActionProxy实现的,其实就是调用了ActionProxy.execute()方法,而该方法又调用了ActionInvocation.invoke()方法。归根到底,最后调用的是DefaultActionInvocation.invokeAction()方法。先看DefaultActionInvocation的init方法。

[java] view plain copy
  1.     /* 
  2.      * (non-Javadoc) 
  3.      * @see com.opensymphony.xwork2.ActionInvocation#init(com.opensymphony.xwork2.ActionProxy) 
  4.      */  
  5.     public void init(ActionProxy proxy) {  
  6.         this.proxy = proxy;  
  7.         Map<String, Object> contextMap = createContextMap();  
  8.   
  9.         // Setting this so that other classes, like object factories, can use the ActionProxy and other  
  10.         // contextual information to operate  
  11.         ActionContext actionContext = ActionContext.getContext();  
  12.   
  13.         if (actionContext != null) {  
  14.             actionContext.setActionInvocation(this);  
  15.         }  
  16.         //创建Action,可Struts2里是每次请求都新建一个Action  
  17.         createAction(contextMap);  
  18.   
  19.         if (pushAction) {  
  20.             stack.push(action);  
  21.             //将创建的action放置到的  
  22.             contextMap.put("action", action);  
  23.         }  
  24.         //将contextMap进行封装  
  25.         invocationContext = new ActionContext(contextMap);  
  26.         invocationContext.setName(proxy.getActionName());  
  27.   
  28.         // get a new List so we don't get problems with the iterator if someone changes the list  
  29.         List<InterceptorMapping> interceptorList = new ArrayList<InterceptorMapping>(proxy.getConfig().getInterceptors());  
  30.         interceptors = interceptorList.iterator();  
  31.     }  
  32.   
  33.     protected void createAction(Map<String, Object> contextMap) {  
  34.         // load action  
  35.         String timerKey = "actionCreate: " + proxy.getActionName();  
  36.         try {  
  37.             UtilTimerStack.push(timerKey);   
  38.             /* 
  39.              * 默认建立Action是StrutsObjectFactory, 
  40.              * 实际中可以是使用Spring创建的Action,这个时候使用的是SpringObjectFactory 
  41.              */              
  42.             action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);  
  43.         } catch (InstantiationException e) {  
  44.             throw new XWorkException("Unable to intantiate Action!", e, proxy.getConfig());  
  45.         } catch (IllegalAccessException e) {  
  46.             throw new XWorkException("Illegal access to constructor, is it public?", e, proxy.getConfig());  
  47.         } catch (Exception e) {  
  48.             String gripe = "";  
  49.   
  50.             if (proxy == null) {  
  51.                 gripe = "Whoa!  No ActionProxy instance found in current ActionInvocation.  This is bad ... very bad";  
  52.             } else if (proxy.getConfig() == null) {  
  53.                 gripe = "Sheesh.  Where'd that ActionProxy get to?  I can't find it in the current ActionInvocation!?";  
  54.             } else if (proxy.getConfig().getClassName() == null) {  
  55.                 gripe = "No Action defined for '" + proxy.getActionName() + "' in namespace '" + proxy.getNamespace() + "'";  
  56.             } else {  
  57.                 gripe = "Unable to instantiate Action, " + proxy.getConfig().getClassName() + ",  defined for '" + proxy.getActionName() + "' in namespace '" + proxy.getNamespace() + "'";  
  58.             }  
  59.   
  60.             gripe += (((" -- " + e.getMessage()) != null) ? e.getMessage() : " [no message in exception]");  
  61.             throw new XWorkException(gripe, e, proxy.getConfig());  
  62.         } finally {  
  63.             UtilTimerStack.pop(timerKey);  
  64.         }  
  65.   
  66.         if (actionEventListener != null) {  
  67.             action = actionEventListener.prepare(action, stack);  
  68.         }  
  69.     }  
接下来看看DefaultActionInvocation 的invoke方法:

[java] view plain copy
  1.     /* 
  2.      * invoke()方法中的if(interceptors.hasNext())语句, 
  3.      * 当然,interceptors里存储的是interceptorMapping列表(它包括一个Interceptor和一个name), 
  4.      * 所有的截拦器必须实现Interceptor的intercept()方法, 
  5.      * 而该方法的参数恰恰又是ActionInvocation,在intercept方法中还是调用invocation.invoke(), 
  6.      * 从而实现了一个Interceptor链的调用。当所有的Interceptor执行完, 
  7.      * 最后调用invokeActionOnly方法来执行Action相应的方法。 
  8.      */  
  9.     public String invoke() throws Exception {  
  10.         String profileKey = "invoke: ";  
  11.         try {  
  12.             UtilTimerStack.push(profileKey);  
  13.   
  14.             if (executed) {  
  15.                 throw new IllegalStateException("Action has already executed");  
  16.             }  
  17.             // 判断interceptors是否有拦截器  
  18.             if (interceptors.hasNext()) {  
  19.                 final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();  
  20.                 String interceptorMsg = "interceptor: " + interceptor.getName();  
  21.                 UtilTimerStack.push(interceptorMsg);  
  22.                 try {  
  23.                     //执行拦截器,返回一个字符串返回代码  
  24.                     resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);  
  25.                 }finally {  
  26.                     UtilTimerStack.pop(interceptorMsg);  
  27.                 }  
  28.             } else {  
  29.                 //interceptor执行完了之后执行action  
  30.                 resultCode = invokeActionOnly();  
  31.             }  
  32.   
  33.             // this is needed because the result will be executed, then control will return to the Interceptor, which will  
  34.             // return above and flow through again  
  35.             if (!executed) {  
  36.                  //在Result返回之前调用preResultListeners  
  37.                 if (preResultListeners != null) {  
  38.                     for (Object preResultListener : preResultListeners) {  
  39.                         PreResultListener listener = (PreResultListener) preResultListener;  
  40.   
  41.                         String _profileKey = "preResultListener: ";  
  42.                         try {  
  43.                             UtilTimerStack.push(_profileKey);  
  44.                             listener.beforeResult(this, resultCode);  
  45.                         }  
  46.                         finally {  
  47.                             UtilTimerStack.pop(_profileKey);  
  48.                         }  
  49.                     }  
  50.                 }  
  51.   
  52.                 // now execute the result, if we're supposed to  
  53.                 if (proxy.getExecuteResult()) {  
  54.                     /* 
  55.                      * action执行完了,还要根据ResultConfig返回到view, 
  56.                      * 也就是在invoke方法中调用executeResult方法 
  57.                      */  
  58.                     executeResult();  
  59.                 }  
  60.   
  61.                 executed = true;  
  62.             }  
  63.             //返回代理执行Action后的回的字符串  
  64.             return resultCode;  
  65.         }  
  66.         finally {  
  67.             UtilTimerStack.pop(profileKey);  
  68.         }  
  69.     }  

调用invokeActionOnly方法来执行Action相应的方法:

[java] view plain copy
  1.     public String invokeActionOnly() throws Exception {  
  2.         return invokeAction(getAction(), proxy.getConfig());  
  3.     }  
  4.   
  5.     protected String invokeAction(Object action, ActionConfig actionConfig) throws Exception {  
  6.         //通过代理proxy.获得方法名称  
  7.         String methodName = proxy.getMethod();  
  8.   
  9.         if (LOG.isDebugEnabled()) {  
  10.             LOG.debug("Executing action method = " + actionConfig.getMethodName());  
  11.         }  
  12.   
  13.         String timerKey = "invokeAction: " + proxy.getActionName();  
  14.         try {  
  15.             UtilTimerStack.push(timerKey);  
  16.   
  17.             boolean methodCalled = false;  
  18.             Object methodResult = null;  
  19.             Method method = null;  
  20.             try {  
  21.                 //java反射机制得到要执行的方法  
  22.                 method = getAction().getClass().getMethod(methodName, EMPTY_CLASS_ARRAY);  
  23.             } catch (NoSuchMethodException e) {  
  24.                 // hmm -- OK, try doXxx instead  
  25.                 try {  
  26.                      //如果没有对应的方法,则使用do+Xxxx来再次获得方法    
  27.                     String altMethodName = "do" + methodName.substring(01).toUpperCase() + methodName.substring(1);  
  28.                     method = getAction().getClass().getMethod(altMethodName, EMPTY_CLASS_ARRAY);  
  29.                 } catch (NoSuchMethodException e1) {  
  30.                     // well, give the unknown handler a shot  
  31.                     //当未知的action、result或者方法被执行的时候,通过框架被调用。  
  32.                     if (unknownHandlerManager.hasUnknownHandlers()) {  
  33.                         try {  
  34.                             methodResult = unknownHandlerManager.handleUnknownMethod(action, methodName);  
  35.                             methodCalled = true;  
  36.                         } catch (NoSuchMethodException e2) {  
  37.                             // throw the original one  
  38.                             throw e;  
  39.                         }  
  40.                     } else {  
  41.                         throw e;  
  42.                     }  
  43.                 }  
  44.             }  
  45.             //执行Method  
  46.             if (!methodCalled) {  
  47.                 methodResult = method.invoke(action, EMPTY_OBJECT_ARRAY);  
  48.             }  
  49.   
  50.             return saveResult(actionConfig, methodResult);  
  51.         } catch (NoSuchMethodException e) {  
  52.             //无法找到某一特定方法时,抛出该(NoSuchMethodException)异常  
  53.             throw new IllegalArgumentException("The " + methodName + "() is not defined in action " + getAction().getClass() + "");  
  54.         } catch (InvocationTargetException e) {  
  55.             // We try to return the source exception.  
  56.             Throwable t = e.getTargetException();  
  57.   
  58.             if (actionEventListener != null) {  
  59.                 String result = actionEventListener.handleException(t, getStack());  
  60.                 if (result != null) {  
  61.                     return result;  
  62.                 }  
  63.             }  
  64.             if (t instanceof Exception) {  
  65.                 throw (Exception) t;  
  66.             } else {  
  67.                 throw e;  
  68.             }  
  69.         } finally {  
  70.             UtilTimerStack.pop(timerKey);  
  71.         }  
  72.     }  
action执行完了,还要根据ResultConfig返回到view,也就是在invoke方法中调用executeResult方法:

[java] view plain copy
  1.     private void executeResult() throws Exception {  
  2.         //根据ResultConfig创建Result     
  3.         result = createResult();  
  4.   
  5.         String timerKey = "executeResult: " + getResultCode();  
  6.         try {  
  7.             UtilTimerStack.push(timerKey);  
  8.             if (result != null) {  
  9.                 /* 
  10.                  * 开始执行Result, 
  11.                  * 可以参考Result的实现,如用了比较多的ServletDispatcherResult, 
  12.                  * ServletActionRedirectResult,ServletRedirectResult 
  13.                  */     
  14.                 result.execute(this);  
  15.             } else if (resultCode != null && !Action.NONE.equals(resultCode)) {  
  16.                 throw new ConfigurationException("No result defined for action " + getAction().getClass().getName()  
  17.                         + " and result " + getResultCode(), proxy.getConfig());  
  18.             } else {  
  19.                 if (LOG.isDebugEnabled()) {  
  20.                     LOG.debug("No result returned for action " + getAction().getClass().getName() + " at " + proxy.getConfig()  
  21.               .getLocation());  
  22.                 }  
  23.             }  
  24.         } finally {  
  25.             UtilTimerStack.pop(timerKey);  
  26.         }  
  27.     }  
  28.   
  29.     public Result createResult() throws Exception {  
  30.          //如果Action中直接返回的Result类型,在invokeAction()保存在explicitResult     
  31.         if (explicitResult != null) {  
  32.             Result ret = explicitResult;  
  33.             explicitResult = null;  
  34.   
  35.             return ret;  
  36.         }  
  37.         //根据result名称获得ResultConfig,resultCode就是result的name  
  38.         ActionConfig config = proxy.getConfig();  
  39.         Map<String, ResultConfig> results = config.getResults();  
  40.   
  41.         ResultConfig resultConfig = null;  
  42.   
  43.         try {  
  44.             //通过返回的String来匹配resultConfig   
  45.             resultConfig = results.get(resultCode);  
  46.         } catch (NullPointerException e) {  
  47.             // swallow  
  48.         }  
  49.           
  50.         if (resultConfig == null) {  
  51.             // If no result is found for the given resultCode, try to get a wildcard '*' match.  
  52.             //如果找不到对应name的ResultConfig,则使用name为通配符*的Result       
  53.             //说明可以用*通配所有的Result  
  54.             resultConfig = results.get("*");  
  55.         }  
  56.   
  57.         if (resultConfig != null) {  
  58.             try {  
  59.                 //构造result   
  60.                 return objectFactory.buildResult(resultConfig, invocationContext.getContextMap());  
  61.             } catch (Exception e) {  
  62.                 LOG.error("There was an exception while instantiating the result of type " + resultConfig.getClassName(), e);  
  63.                 throw new XWorkException(e, resultConfig);  
  64.             }  
  65.         } else if (resultCode != null && !Action.NONE.equals(resultCode) && unknownHandlerManager.hasUnknownHandlers()) {  
  66.             return unknownHandlerManager.handleUnknownResult(invocationContext, proxy.getActionName(), proxy.getConfig(), resultCode);  
  67.         }  
  68.         return null;  
  69.     }  
  70.   
  71.     public Result buildResult(ResultConfig resultConfig, Map<String, Object> extraContext) throws Exception {  
  72.           
  73.         String resultClassName = resultConfig.getClassName();  
  74.         Result result = null;  
  75.         if (resultClassName != null) {  
  76.             /* 
  77.              * buildBean中会用反射机制Class.newInstance来创建bean, 
  78.              * 因为Result是有状态的,所以每次请求都新建一个 
  79.              */   
  80.             result = (Result) buildBean(resultClassName, extraContext);  
  81.             Map<String, String> params = resultConfig.getParams();  
  82.             if (params != null) {  
  83.                 for (Map.Entry<String, String> paramEntry : params.entrySet()) {  
  84.                     try {  
  85.                         /* 
  86.                          * reflectionProvider参见OgnlReflectionProvider 
  87.                          * resultConfig.getParams()就是result配置文件里所配置的参数<param></param> 
  88.                          * setProperties方法最终调用的是Ognl类的setValue方法 
  89.                          * 这句其实就是把param名值设置到根对象result上 
  90.                          */  
  91.                         reflectionProvider.setProperty(paramEntry.getKey(), paramEntry.getValue(), result, extraContext, true);  
  92.                     } catch (ReflectionException ex) {  
  93.                         if (result instanceof ReflectionExceptionHandler) {  
  94.                             ((ReflectionExceptionHandler) result).handle(ex);  
  95.                         }  
  96.                     }  
  97.                 }  
  98.             }  
  99.         }  
  100.   
  101.         return result;  
  102.     }