Struts2 加载多个配置文件

本文介绍两种Struts2框架中加载多个配置文件的方法:一是通过struts.xml文件的include特性;二是通过覆盖FilterDispatcher类的方式实现,并提供具体实现步骤及代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Struts2 加载多个配置文件

 

方法1

struts.xml文件中 使用include方式 可以加载多个配置文件,(struts.xmlstruts-default.xmlstrut2默认自动加载的配置文件)

 

方法2

覆盖FilterDispatcher类的方法实现多个配置文件的加载

 

1.重写FilterDispatcher 类的三个方法,我的struts-*.xml的路径在WEB-INF/modules/struts文件夹下,JLTEnvironment类为我的应用的配置路径
public class JLTFilterDispatcher extends FilterDispatcher {
@Override
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);
}
// 加载modules下的struts配置文件
getStrutsConfig(params);
return new Dispatcher(filterConfig.getServletContext(), params);
}
  * 加载modules下的struts配置文件
private void getStrutsConfig(Map<String, String> m) {
String strutsPath = new String(
"struts-default.xml,struts-plugin.xml,struts.xml");
File f = new File(JLTEnvironment.getModulesHome()+"/struts");

if (f.getName().equals("struts")) {
File[] ff = f.listFiles();
if (ff != null && ff.length > 0) {
for (int i = 0; i < ff.length; i++) {
String fname = ff[i].getName();

if (fname.startsWith("struts-") && fname.endsWith(".xml")) {
strutsPath+=","+ff[i].getAbsolutePath();
}
}
}
}

m.put("config", strutsPath);

}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//获得应用的路径
  ServletContext ctx = filterConfig.getServletContext();
  String home = ctx.getRealPath("/");
  home = home.replace('\\', '/');
  if (!home.endsWith("/")) {
  home = home + "/";
  }//初始化应用环境参数
JLTEnvironment.init(home, ctx);
super.init(filterConfig);
}

}
2.web.xml更改为
  <filter>
<filter-name>struts2</filter-name>
<filter-class>
com.jlt.core.JLTFilterDispatcher
</filter-class>
</filter>
3.这样,WEB-INF/modules/struts下的所有以struts-开关的以xml结尾的xml文件都会被自动加载进去,不用去改其它配置了,呵呵

<!--EndFragment-->

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值