在Struts1中如何自己加载struts_config.xml?

为了实现模块化开发,struts_config.xml想放在各个plugin代码之下,如何扩展ActionServlet来读入这些分散的配置文件?

如果看过struts的源码,了解struts的初期加载过程的话,就该知道在struts中可以覆写ActionServlet的initModuleConfig方法来实现自己的加载封装。

举例说一下:

假如你的模块都放在WEB-INF\plugin之下:
[list][*]WEB-INF\plugin\cms\
[*]WEB-INF\plugin\blog\
[*]WEB-INF\plugin\member\
[*]WEB-INF\plugin\space\
[*]...[/list]

而struts_config.xml文件就在每个plugin的根目录下:
如:WEB-INF\plugin\cms\struts_config.xml

那么就可以如下扩展ActionServlet来实现自定义加载:
[code="java"]
public class BaseServlet extends ActionServlet {

protected ModuleConfig initModuleConfig(String prefix, String paths)
        throws ServletException {

    // Parse the configuration for this module
    ModuleConfigFactory factoryObject = ModuleConfigFactory.createFactory();
    ModuleConfig config = factoryObject.createModuleConfig(prefix);

    // Configure the Digester instance we will use
    Digester digester = initConfigDigester();

    String path = getServletContext().getRealPath("/");
    String pluginPath = path + "WEB-INF" + File.separator + "plugin";

    try {

        File[] files = new File(pluginPath).listFiles();
        for (int intCnt = 0; intCnt < files.length; intCnt++) {
            if (files[intCnt].isDirectory()) {
                digester.push(config);
                String configPath = files[intCnt].getAbsolutePath()
                        + File.separator + "struts_config.xml";
                if(new File(configPath).exists()) {

                    String pp = configPath.substring(getServletContext().getRealPath("/").length() - 1).replace('\\', '/');;
                    System.out.println(pp);

                    parseModuleConfigFile(digester, getServletContext().getResource(pp));
                }
            }
        }

    } catch (MalformedURLException e) {
        throw new UnavailableException(e.getMessage());
    }

    getServletContext().setAttribute(
            Globals.MODULE_KEY + config.getPrefix(), config);

    return config;
}

}
[/code]

其实只要在主struts_config.xml里把其他的struts的xml include进来就好了
在struts_config.xml里加上

或者在web.xml里config文件配置多个xml试试

config <!—config指明Struts应用程序的配置文件相对位置-->
/WEB-INF/struts-config.xml


config
/WEB-INF/struts-config-registration.xml

中间用,分隔
[code="xml"]
org.apache.struts.action.ActionServlet

config
/WEB-INF/struts-config.xml,/WEB-INF/struts-config-system.xml,。。。。。。。

[/code]