首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

应用ConfigurationFactory加载context-param中的配置文件

2012-11-10 
使用ConfigurationFactory加载context-param中的配置文件web.xml里面可以定义两种参数:(1)application范围

使用ConfigurationFactory加载context-param中的配置文件

web.xml里面可以定义两种参数:
(1)application范围内的参数,存放在servletcontext中,在web.xml中配置如下:

<context-param>           <param-name>configUrl</param-name>           <param-value>avalible during application</param-value>  </context-param>

?
?? 用getServletContext().getInitParameter("configUrl"))获取

(2)servlet内的初始化参数,,在web.xml中配置如下:

<servlet>    <servlet-name>MainServlet</servlet-name>    <servlet-class>com.wes.controller.MainServlet</servlet-class>    <init-param>       <param-name>param1</param-name>       <param-value>avalible in servlet init()</param-value>    </init-param>    <load-on-startup>0</load-on-startup></servlet>

?

只能在servlet的init()方法中用this.getInitParameter("param1"));得到

?

使用ConfigurationFactory获取参数:

ConfigurationFactory(String configurationFileName)    //The path to the configuration file    //此处path是绝对路径,所以必须context.getRealPath(..);

?例子:
web.xml中:

<context-param>        <param-name>configUrl</param-name>        <param-value>WEB-INF/config.xml</param-value>     </context-param>

?

WEB-INF? -> config.xml中:

<?xml version="1.0" encoding="UTF-8"?>    <configuration>        <xml fileName="config/AbacusCfg.xml" />        <xml fileName="config/emailconfig.xml" />        <properties fileName="global.properties"/>    </configuration>

?

WEB-INF -> config -> emailconfig.xml:

 <?xml version="1.0" encoding="UTF-8"?>   <Config>          <b2bEmail>             <receiver>ko@techson.com.hk;</receiver>          </b2bEmail>          <packageb2cemail>             af@techson.com.hk;alex@techson.com.hk          </packageb2cemail>          ...  </Config>
?

?启动时在contextInitialized()方法中获取配置文件:

this.context = sce.getServletContext();    //ServletContextEvent sce    String path = this.context.getRealPath(this.context.getInitParameter("configUrl"));    ConfigurationFactory factory = new ConfigurationFactory(path);    Configuration config = factory.getConfiguration();    this.context.setAttribute(MyConstants.CONFIGURATION_KEY, config);    this.context.setAttribute(MyConstants.GOOGLE_MAP_KEY, config.getString("packageb2cemail"));    //String bkemail = config.getString("b2bEmail.receiver");

?。。。

?

?

热点排行