第一步:配置文件1. web.xml<servlet>
<servlet-name>InitServlet</servlet-name>
<servlet-class>com.0734w.util.InitServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/config.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
2.config.properties假若在config.properties配置如下
app1.name=dog
app2.name=pig
3.在Constants.java中定义public final static String
APP1NAME = "app1.name";
public final static String
APP2NAME = "app2.name";
第二步:定义InitServletpackage com.0734w.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.PropertyResourceBundle;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
import com.cpic.adapter.adapterapp.constant.Constants;
/**
* <p>Title:InitServlet.java</p>
* <p>Description:当应用起动时加载要读取的数据放入context中</p>
* @author spark 2005-12-26
* @version 1.0
*/
public class InitServlet extends HttpServlet {
private Logger logger;
public void init() throws ServletException{
super.init();
ServletContext context = getServletContext();
context.setAttribute(Constants.ADAPTER_INIT_STATUS,Boolean.FALSE);
//initialize proxy configuration
initAdapter();
context.setAttribute(Constants.ADAPTER_INIT_STATUS,Boolean.TRUE);
logger.info("initAdapter initialized successfully");
}
/**
* <p>Description:加载和设置数据</p>
* @throws ServletException
* spark 2005-12-26
*/
private void initAdapter() throws ServletException{
ServletContext context = getServletContext();
String configFile = getInitParameter("config");
if (configFile == null) {
String errMsg="Initialize Adapter configuration config file is not set in web.xml.";
logger.error(errMsg);
ServletException e = new ServletException(errMsg);
throw e;
}
InputStream in;
PropertyResourceBundle configBundle;
try {
in = this.getServletContext().getResourceAsStream(configFile);
configBundle = new PropertyResourceBundle(in);
/
/需要读取的数据每一个数据都要从这里 定义 context.setAttribute(Constants.APP1NAME,configBundle.getString(Constants.APP1NAME));
context.setAttribute(Constants.APP2NAME,configBundle.getString(Constants..APP2NAME)); } catch (IOException e) {
String errMsg = "Initialize adapter config.properties failed.";
logger.error(errMsg);
ServletException e1 = new ServletException(errMsg);
throw e1;
}
catch (Exception e) {
String errMsg = "Initialize adapter config.properties failed.";
logger.error(errMsg);
ServletException e1 = new ServletException(errMsg);
throw e1;
}
}
}
第三步,在应用利用:在servlet中如下:
ServletContext context = getServletContext();
( String) context.getAttribute(
Constants.APP1NAME)
在STRUTS的ACTION中如下:
ServletContext context = request.getSession().getServletContext();
(String) context.getAttribute(
Constants.APP1NAME);