---
title: "Struts2--Dispatcher&ConfigurationProvider"
author: "mujun1209"
date: "2010-10-26T16:39:57Z"
tags: ["Apache", "Bean", "Struts", "Webwork", "XML"]
categories: ["企业架构"]
slug: "struts2-dispatcher-configurationprovider"
draft: false
lastmod: "2010-10-26T16:39:57Z"
id: 794654
url: "https://mujun1209.iteye.com/blog/794654"
---

首先强调一下struts2的线程程安全，在Struts2中大量采用ThreadLocal线程局部变量的方法来保证线程的安全,像Dispatcher等都是通过ThreadLocal来保存变量值,使得每个线程都有自己独立的实例变量,互不相干.

 

接下来就从Dispatcher开始看起，先看其构造函数：

Java代码 [![复制代码](http://qidaoxp.iteye.com/images/icon_copy.gif)](http://qidaoxp.iteye.com/blog/494444 "复制代码")

1. //创建Dispatcher，此类是一个Delegate，它是真正完成根据url解析转向，读取对应Action的地方
2. **public** Dispatcher(ServletContext servletContext, Map&lt;String, String&gt; initParams) {
3. **this**.servletContext = servletContext;
4. //配置在web.xml中的param参数
5. **this**.initParams = initParams;
6. }

```
//创建Dispatcher，此类是一个Delegate，它是真正完成根据url解析转向，读取对应Action的地方
    public Dispatcher(ServletContext servletContext, Map<String, String> initParams) {
        this.servletContext = servletContext;
		//配置在web.xml中的param参数
        this.initParams = initParams;
    }
```

 

我们再看在FilterDispatcher创建Dispatcher的:

Java代码 [![复制代码](http://qidaoxp.iteye.com/images/icon_copy.gif)](http://qidaoxp.iteye.com/blog/494444 "复制代码")

01. **protected** Dispatcher createDispatcher(FilterConfig filterConfig) {
02. Map&lt;String, String&gt; params = **new** HashMap&lt;String, String&gt;();
03. **for** (Enumeration e = filterConfig.getInitParameterNames(); e.hasMoreElements();) {
04. String name = (String) e.nextElement();
05. String value = filterConfig.getInitParameter(name);
06. params.put(name, value);
07. }
08. 都可以从FilterConfig中得到
09. **return** **new** Dispatcher(filterConfig.getServletContext(), params);
10. }

```
    protected Dispatcher createDispatcher(FilterConfig filterConfig) {
        Map<String, String> params = new HashMap<String, String>();
        for (Enumeration e = filterConfig.getInitParameterNames(); e.hasMoreElements();) {
            String name = (String) e.nextElement();
            String value = filterConfig.getInitParameter(name);
            params.put(name, value);
        }
		//都可以从FilterConfig中得到
        return new Dispatcher(filterConfig.getServletContext(), params);
    }
```

 

创建Dispatcher之后,来看init()方法  
init()方法是用来Load用户配置文件,资源文件以及默认的配置文件.

主要分七步走,看下面注释

Java代码 [![复制代码](http://qidaoxp.iteye.com/images/icon_copy.gif)](http://qidaoxp.iteye.com/blog/494444 "复制代码")

01. **public** **void** init() {
02. **if** (configurationManager == **null**) {
03. //设置ConfigurationManager的defaultFrameworkBeanName.
04. //这里DEFAULT\_BEAN\_NAME为struts,这是xwork框架的内容,Framework可以是xwork,struts,webwork等
05. configurationManager = **new** ConfigurationManager(BeanSelectionProvider.DEFAULT\_BEAN\_NAME);
06. }
07. //读取properties信息,默认的default.properties,
08. init\_DefaultProperties(); // \[1]
09. //读取xml配置文件
10. init\_TraditionalXmlConfigurations(); // \[2]
11. //读取用户自定义的struts.properties
12. init\_LegacyStrutsProperties(); // \[3]
13. //自定义的configProviders
14. init\_CustomConfigurationProviders(); // \[5]
15. //载入FilterDispatcher传进来的initParams
16. init\_FilterInitParameters() ; // \[6]
17. //将配置文件中的bean与具体的类映射
18. init\_AliasStandardObjects() ; // \[7]
19. //构建一个用于依赖注射的Container对象
20. //在这里面会循环调用上面七个ConfigurationProvider的register方法
21. //其中的重点就是DefaultConfiguration的#reload()方法
22. Container container = init\_PreloadConfiguration();
23. container.inject(**this**);
24. init\_CheckConfigurationReloading(container);
25. init\_CheckWebLogicWorkaround(container);
26. **if** (!dispatcherListeners.isEmpty()) {
27. **for** (DispatcherListener l : dispatcherListeners) {
28. l.dispatcherInitialized(**this**);
29. }
30. }
31. }

```
    public void init() {

    	if (configurationManager == null) {
		    //设置ConfigurationManager的defaultFrameworkBeanName.
			//这里DEFAULT_BEAN_NAME为struts,这是xwork框架的内容,Framework可以是xwork,struts,webwork等
    		configurationManager = new ConfigurationManager(BeanSelectionProvider.DEFAULT_BEAN_NAME);
    	}
        //读取properties信息,默认的default.properties,
    	init_DefaultProperties(); // [1]
		//读取xml配置文件
        init_TraditionalXmlConfigurations(); // [2]
		//读取用户自定义的struts.properties
        init_LegacyStrutsProperties(); // [3]
		//自定义的configProviders
        init_CustomConfigurationProviders(); // [5]
		//载入FilterDispatcher传进来的initParams
        init_FilterInitParameters() ; // [6]
		//将配置文件中的bean与具体的类映射
        init_AliasStandardObjects() ; // [7]
        
		//构建一个用于依赖注射的Container对象
		//在这里面会循环调用上面七个ConfigurationProvider的register方法
		//其中的重点就是DefaultConfiguration的#reload()方法
        Container container = init_PreloadConfiguration();
        container.inject(this);
        init_CheckConfigurationReloading(container);
        init_CheckWebLogicWorkaround(container);

        if (!dispatcherListeners.isEmpty()) {
            for (DispatcherListener l : dispatcherListeners) {
                l.dispatcherInitialized(this);
            }
        }
    }
```

 

分七步载入各种配置属性,都是通过ConfigurationProvider接口进行的,这个接口提供init(),destroy(),register()等方法.  
将各种ConfigurationProvider初始化之后将实例添加到ConfigurationManager的List里面.  
最后通过循环调用List里的这些destroy(),register()等方法实现对配置文件的属性进行注册和销毁等功能.  
下面将分析这七层功夫是怎样一步步练成的.

 

首先是init\_DefaultProperties()

Java代码 [![复制代码](http://qidaoxp.iteye.com/images/icon_copy.gif)](http://qidaoxp.iteye.com/blog/494444 "复制代码")

01. **private** **void** init\_DefaultProperties() {
02. configurationManager.addConfigurationProvider(**new** DefaultPropertiesProvider());
03. }
04. 接来看DefaultPropertiesProvider好了,DefaultPropertiesProvider实际上只是实现了register()方法
05. **public** **void** register(ContainerBuilder builder, LocatableProperties props)
06. **throws** ConfigurationException {
07. Settings defaultSettings = **null**;
08. **try** {
09. defaultSettings = **new** PropertiesSettings("org/apache/struts2/default");
10. } **catch** (Exception e) {
11. **throw** **new** ConfigurationException("Could not find or error in org/apache/struts2/default.properties", e);
12. }
13. loadSettings(props, defaultSettings);
14. }

```
    private void init_DefaultProperties() {
        configurationManager.addConfigurationProvider(new DefaultPropertiesProvider());
    }
	//直接来看DefaultPropertiesProvider好了,DefaultPropertiesProvider实际上只是实现了register()方法
    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);
    }
```

 

Java代码 [![复制代码](http://qidaoxp.iteye.com/images/icon_copy.gif)](http://qidaoxp.iteye.com/blog/494444 "复制代码")

01. //PropertiesSettings构造方法
02. //读取org/apache/struts2/default.properties的配置信息，如果项目中需要覆盖，可以在classpath里的struts.properties里覆写
03. **public** PropertiesSettings(String name) {
04. URL settingsUrl = ClassLoaderUtils.getResource(name + ".properties", getClass());
05. **if** (settingsUrl == **null**) {
06. LOG.debug(name + ".properties missing");
07. settings = **new** LocatableProperties();
08. **return**;
09. }
10. settings = **new** LocatableProperties(**new** LocationImpl(**null**, settingsUrl.toString()));
11. // Load settings
12. InputStream in = **null**;
13. **try** {
14. in = settingsUrl.openStream();
15. settings.load(in);
16. } **catch** (IOException e) {
17. **throw** **new** StrutsException("Could not load " + name + ".properties:" + e, e);
18. } **finally** {
19. **if**(in != **null**) {
20. **try** {
21. in.close();
22. } **catch**(IOException io) {
23. LOG.warn("Unable to close input stream", io);
24. }
25. }
26. }
27. }
28. //loadSettings主要是将progerty的value和Locale从上面PropertiesSettings中取得并存放到LocatableProperties props
29. //这个props是register的一个入参.
30. **protected** **void** loadSettings(LocatableProperties props, **final** Settings settings) {
31. // We are calling the impl methods to get around the single instance of Settings that is expected
32. **for** (Iterator i = settings.listImpl(); i.hasNext(); ) {
33. String name = (String) i.next();
34. props.setProperty(name, settings.getImpl(name), settings.getLocationImpl(name));
35. }
36. }

```
//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);
                }
            }
        }
    }
	
	//loadSettings主要是将progerty的value和Locale从上面PropertiesSettings中取得并存放到LocatableProperties props
	//这个props是register的一个入参.
    protected void loadSettings(LocatableProperties props, final Settings settings) {
        // We are calling the impl methods to get around the single instance of Settings that is expected
        for (Iterator i = settings.listImpl(); i.hasNext(); ) {
            String name = (String) i.next();
            props.setProperty(name, settings.getImpl(name), settings.getLocationImpl(name));
        }
    }	
```

 

 

再来看第二步：init\_TraditionalXmlConfigurations()

Java代码 [![复制代码](http://qidaoxp.iteye.com/images/icon_copy.gif)](http://qidaoxp.iteye.com/blog/494444 "复制代码")

01. **private** **void** init\_TraditionalXmlConfigurations() {
02. //首先读取web.xml中的config初始参数值
03. //如果没有配置就使用默认的DEFAULT\_CONFIGURATION\_PATHS:"struts-default.xml,struts-plugin.xml,struts.xml"，
04. //这儿就可以看出为什么默认的配置文件必须取名为这三个名称了
05. //如果不想使用默认的名称，直接在web.xml中配置config初始参数即可
06. String configPaths = initParams.get("config");
07. **if** (configPaths == **null**) {
08. configPaths = DEFAULT\_CONFIGURATION\_PATHS;
09. }
10. String\[] files = configPaths.split("\\\\s\*\[,]\\\\s\*");
11. **for** (String file : files) {
12. **if** (file.endsWith(".xml")) {
13. **if** ("xwork.xml".equals(file)) {
14. //XmlConfigurationProvider负责解析xwork.xml
15. configurationManager.addConfigurationProvider(**new** XmlConfigurationProvider(file, **false**));
16. } **else** {
17. //其它xml都是由StrutsXmlConfigurationProvider来解析
18. configurationManager.addConfigurationProvider(**new** StrutsXmlConfigurationProvider(file, **false**, servletContext));
19. }
20. } **else** {
21. **throw** **new** IllegalArgumentException("Invalid configuration file name");
22. }
23. }
24. }

```
    private void init_TraditionalXmlConfigurations() {
	    //首先读取web.xml中的config初始参数值   
        //如果没有配置就使用默认的DEFAULT_CONFIGURATION_PATHS:"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*");
        for (String file : files) {
            if (file.endsWith(".xml")) {
                if ("xwork.xml".equals(file)) {
				    //XmlConfigurationProvider负责解析xwork.xml
                    configurationManager.addConfigurationProvider(new XmlConfigurationProvider(file, false));
                } else {
				    //其它xml都是由StrutsXmlConfigurationProvider来解析
                    configurationManager.addConfigurationProvider(new StrutsXmlConfigurationProvider(file, false, servletContext));
                }
            } else {
                throw new IllegalArgumentException("Invalid configuration file name");
            }
        }
    }
```

 

对于其它配置文件只用StrutsXmlConfigurationProvider，此类继承XmlConfigurationProvider，而XmlConfigurationProvider又实现ConfigurationProvider接口。  
类XmlConfigurationProvider负责配置文件的读取和解析，  
首先通过init()中的loadDocuments(configFileName);利用DomHelper中的  
public static Document parse(InputSource inputSource, Map&lt;String, String&gt; dtdMappings) 将configFileName配置文件通过SAX解析方式按照DtdMappings解析成Document对象.  
然后通过Provider的register()方法加载"bean"和"constant"属性,再通过loadPackages()加载package及package中的属性  
addAction()方法负责读取&lt;action&gt;标签，并将数据保存在ActionConfig中；  
addResultTypes()方法负责将&lt;result-type&gt;标签转化为ResultTypeConfig对象；  
loadInterceptors()方法负责将&lt;interceptor&gt;标签转化为InterceptorConfi对象；  
loadInterceptorStack()方法负责将&lt;interceptor-ref&gt;标签转化为InterceptorStackConfig对象；  
loadInterceptorStacks()方法负责将&lt;interceptor-stack&gt;标签转化成InterceptorStackConfig对象。  
而上面的方法最终会被addPackage()方法调用,addPackage又会被Provider的loadPackages()调用，将所读取到的数据汇集到PackageConfig对象中。

Java代码 [![复制代码](http://qidaoxp.iteye.com/images/icon_copy.gif)](http://qidaoxp.iteye.com/blog/494444 "复制代码")

01. **protected** PackageConfig addPackage(Element packageElement) **throws** ConfigurationException {
02. PackageConfig.Builder newPackage = buildPackageContext(packageElement);
03. **if** (newPackage.isNeedsRefresh()) {
04. **return** newPackage.build();
05. }
06. // add result types (and default result) to this package
07. addResultTypes(newPackage, packageElement);
08. // load the interceptors and interceptor stacks for this package
09. loadInterceptors(newPackage, packageElement);
10. // load the default interceptor reference for this package
11. loadDefaultInterceptorRef(newPackage, packageElement);
12. // load the default class ref for this package
13. loadDefaultClassRef(newPackage, packageElement);
14. // load the global result list for this package
15. loadGlobalResults(newPackage, packageElement);
16. // load the global exception handler list for this package
17. loadGobalExceptionMappings(newPackage, packageElement);
18. // get actions
19. NodeList actionList = packageElement.getElementsByTagName("action");
20. **for** (**int** i = 0; i &lt; actionList.getLength(); i++) {
21. Element actionElement = (Element) actionList.item(i);
22. addAction(actionElement, newPackage);
23. }
24. // load the default action reference for this package
25. loadDefaultActionRef(newPackage, packageElement);
26. PackageConfig cfg = newPackage.build();
27. configuration.addPackageConfig(cfg.getName(), cfg);
28. **return** cfg;
29. }
30. loadConfigurationFiles解析读取xml中的内容
31. **private** List&lt;Document&gt; loadConfigurationFiles(String fileName, Element includeElement) {
32. ...
33. //通过DomHelper调用SAX进行解析xml
34. doc = DomHelper.parse(in, dtdMappings);
35. ...
36. Element rootElement = doc.getDocumentElement();
37. NodeList children = rootElement.getChildNodes();
38. **int** childSize = children.getLength();
39. **for** (**int** i = 0; i &lt; childSize; i++) {
40. Node childNode = children.item(i);
41. **if** (childNode **instanceof** Element) {
42. Element child = (Element) childNode;
43. **final** String nodeName = child.getNodeName();
44. **if** ("include".equals(nodeName)) {
45. String includeFileName = child.getAttribute("file");
46. //解析每个action配置是，对于include文件可以使用通配符\*来进行配置
47. //如Struts.xml中可配置成&lt;include file="actions\_\*.xml"/&gt;
48. **if** (includeFileName.indexOf('\*') != -1) {
49. ClassPathFinder wildcardFinder = **new** ClassPathFinder();
50. wildcardFinder.setPattern(includeFileName);
51. Vector&lt;String&gt; wildcardMatches = wildcardFinder.findMatches();
52. **for** (String match : wildcardMatches) {
53. //递归Load子file中的&lt;include/&gt;
54. docs.addAll(loadConfigurationFiles(match, child));
55. }
56. } **else** {
57. docs.addAll(loadConfigurationFiles(includeFileName, child));
58. }
59. }
60. }
61. }
62. docs.add(doc);
63. loadedFileUrls.add(url.toString());
64. ...
65. **return** docs;
66. }

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

        if (newPackage.isNeedsRefresh()) {
            return newPackage.build();
        }
        // add result types (and default result) to this package
        addResultTypes(newPackage, packageElement);
        // load the interceptors and interceptor stacks for this package
        loadInterceptors(newPackage, packageElement);
        // load the default interceptor reference for this package
        loadDefaultInterceptorRef(newPackage, packageElement);
        // load the default class ref for this package
        loadDefaultClassRef(newPackage, packageElement);
        // load the global result list for this package
        loadGlobalResults(newPackage, packageElement);
        // load the global exception handler list for this package
        loadGobalExceptionMappings(newPackage, packageElement);
        // get actions
        NodeList actionList = packageElement.getElementsByTagName("action");
        for (int i = 0; i < actionList.getLength(); i++) {
            Element actionElement = (Element) actionList.item(i);
            addAction(actionElement, newPackage);
        }
        // load the default action reference for this package
        loadDefaultActionRef(newPackage, packageElement);
        PackageConfig cfg = newPackage.build();
        configuration.addPackageConfig(cfg.getName(), cfg);
        return cfg;
    }	
	
	//loadConfigurationFiles解析读取xml中的内容
    private List<Document> loadConfigurationFiles(String fileName, Element includeElement) {      
      ...  
	  //通过DomHelper调用SAX进行解析xml
	  doc = DomHelper.parse(in, dtdMappings);
	  ...
      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();

          if ("include".equals(nodeName)) {
            String includeFileName = child.getAttribute("file");
			
	        //解析每个action配置是，对于include文件可以使用通配符*来进行配置   
            //如Struts.xml中可配置成<include file="actions_*.xml"/>  
            if (includeFileName.indexOf('*') != -1) {
              ClassPathFinder wildcardFinder = new ClassPathFinder();
              wildcardFinder.setPattern(includeFileName);
              Vector<String> wildcardMatches = wildcardFinder.findMatches();
              for (String match : wildcardMatches) {
		        //递归Load子file中的<include/>
                docs.addAll(loadConfigurationFiles(match, child));
              }
            } else {

              docs.addAll(loadConfigurationFiles(includeFileName, child));
            }
          }
        }
      }
      docs.add(doc);
      loadedFileUrls.add(url.toString());
      ...
      return docs;
    }
```