启动tomcat时加载配置文件信息
程序员文章站
2022-05-13 17:43:33
...
1.创建一个class 需要 导入ServletContextListener
package com; import java.io.IOException; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class TestL implements ServletContextListener { public static Properties p = new Properties();; @Override public void contextDestroyed(ServletContextEvent arg0) { //未知调用时刻 System.out.println(111111); } @Override public void contextInitialized(ServletContextEvent event) { ServletContext servletContext = event.getServletContext(); try { p.load(servletContext.getResourceAsStream("/WEB-INF/config/data.properties")); } catch (IOException e) { e.printStackTrace(); } // 在应用启动时候调用 System.out.println(2222); } public static String getProValue(String key) { return p.getProperty(key); } }
2. WEB-INF/config/data.properties 文件
内容:
WCITY.WEATHER.URL=http://218.207.217.158:8080/weather/QueryByCityNameAndReturnJson.do
3.web.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Testxl</display-name>
<listener>
<listener-class>com.TestL</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
4.测试类
package com; public class Pcommon { public void getI(String s) { String ss = TestL.getProValue("WCITY.WEATHER.URL"); System.out.println(ss+"====ddd=="+s); } }