- 1.定义ServletContextListener
public class ApplicationLoader implements ServletContextListener{ private String ip; private String port; private String username; private String password; private String server; |
public void contextInitialized(ServletContextEvent arg0) { //装载配置文件 this.loadXmlConfig(); // 将配置文件里的值装入context属性,这样可以在JSP,SERVLET里调用 ServletContext context = arg0.getServletContext(); context.setAttribute("ip", this.ip); context.setAttribute("port", this.port); context.setAttribute("username", this.username); context.setAttribute("password", this.password); context.setAttribute("server", this.server); } |
public void loadXmlConfig() { //获取配置文件路径, 定义在系统环境变量中 String xmlFile = System.getenv(Constants.ENVNAME); //Dom4J方式获取XML文件的节点值 List<String> retList = null; retList = Dom4JParser.readNodeText(new File( xmlFile+"/ibiconfig/xml/amconfig.xml"),"//host/ip"); if(null != retList){ for(String temp:retList){ this.ip = temp; } } //Dom4J方式获取XML文件的节点值 retList = Dom4JParser.readNodeText(new File( xmlFile+"/ibiconfig/xml/amconfig.xml"),"//host/port"); if(null != retList){ for(String temp:retList){ this.port = temp; } } //Dom4J方式获取XML文件的节点值 retList = Dom4JParser.readNodeText(new File( xmlFile+"/ibiconfig/xml/amconfig.xml"),"//host/authentication/username"); if(null != retList){ for(String temp:retList){ this.username = temp; } } //Dom4J方式获取XML文件的节点值 retList = Dom4JParser.readNodeText(new File( xmlFile+"/ibiconfig/xml/amconfig.xml"),"//host//authentication/password"); if(null != retList){ for(String temp:retList){ this.password = temp; } } //Dom4J方式获取XML文件的节点值 retList = Dom4JParser.readNodeText(new File( xmlFile+"/ibiconfig/xml/amconfig.xml"),"//host//authentication/server"); if(null != retList){ for(String temp:retList){ this.server = temp; } } } |
- 2.修改WEB-INF/web.xml, 启用前面定义的listener
<!-- 系统初始化loader --> <listener> <listener-class>com.machome.system.ApplicationLoader</listener-class> </listener> |
- 3.在JSP页面里可以调用listener装入的变量值
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <br /> <%=getServletContext().getAttribute("ip")%> <br /> <%=getServletContext().getAttribute("username")%> <br /> <%=getServletContext().getAttribute("password")%> <br /> </body> </html> |
<?xml version="1.0" encoding="UTF-8"?> <!-- reload tomcat after changed this file--> <root> <host> <ip>192.168.0.101</ip> <port>8080</port> <authentication> <username>macg</username> <password>008421</password> <server>EDASERVE</server> </authentication> </host> </root> |
前面采用的是读取环境变量获取XML文件路径,我们应该把这个配置文件的路径设到环境变量中.这里不赘述.
你也可以直接采用文件物理路径,访问更简单些,但路径做死在程序里,不好修改.