首先声明,struts1的多模块配置很好很强大很有用,对于大型的web项目来说多模块化是必不可少的,结合合理的分层分包可以实现基本的可组装的业务。扯淡的是其配置方式,完全不人性化,感觉作者是火星人,举个例子:既然模块已经分成单个配置文件了,干嘛还要在web.xml中指定模块名??这不是人为增加了配置环节吗?这个问题在java web开发中大量存在:学院派的思维习惯作祟,今天只是揪住struts1这个倒霉蛋罢了。
觉得不爽还是自己动手吧:扩展struts控制器,自动加载某个目录下所有的***_config.xml,自动将***作为模块名。
package -------------;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.config.ModuleConfig;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import java.io.File;
/**
* <p> 描述: 强化的struts控制器</p>
* 1、强化配置读取,支持从类路径某个目录读取配置,自动按文件名映射模块
* 2、以struts-config为前缀的文件统一映射到默认路径
* <p/>
* <p> Create Date: 2009-4-15 18:34:30 <p>
*
* @author betafox
* @version 1.0
*/
public class StrutsServlet extends ActionServlet {
public void init() throws ServletException {
try {
initInternal();
initOther();
initServlet();
getServletContext().setAttribute(Globals.ACTION_SERVLET_KEY, this);
initModuleConfigFactory();
// Initialize modules as needed
//===============================================
File dir = new File(StrutsServlet.class.getResource("/conf/struts1/").toURI());
File[] xmls = dir.listFiles();
for (int i = 0; i < xmls.length; i++) {
String name = xmls[i].getName();
String prefix = "/" + name.toLowerCase().replace(".xml", "");
if (prefix.startsWith("/struts-config"))
prefix = "";//默认模块
ModuleConfig moduleConfig = initModuleConfig
(prefix, "/conf/struts1/" + name);
initModuleMessageResources(moduleConfig);
initModuleDataSources(moduleConfig);
initModulePlugIns(moduleConfig);
moduleConfig.freeze();
}
//==============================================
this.initModulePrefixes(this.getServletContext());
this.destroyConfigDigester();
} catch (UnavailableException ex) {
throw ex;
} catch (Throwable t) {
log.error("Unable to initialize Struts ActionServlet due to an "
+ "unexpected exception or error thrown, so marking the "
+ "servlet as unavailable. Most likely, this is due to an "
+ "incorrect or missing library dependency.", t);
throw new UnavailableException(t.getMessage());
}
}
}
实现中发现struts1的可扩展性实在是不敢恭维,找不到ActionServlet 的init扩展点,只有重写一下,严重的侵入了...!
有这方面体会和经验的朋友不妨共享一下。