1. 程式人生 > >web 中加載配置文件

web 中加載配置文件

code set 監聽器 XML sign rri ace this keyword

1.web.xml中配置

<!-- 加載配置文件 --> <listener> <description>ServletContextListener</description> <listener-class>com.lanhetech.application.ContextInitListener</listener-class> </listener>

2.加載

import java.io.FileInputStream; import java.util.HashMap;
import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.apache.log4j.Logger; // 加載配置文件到application中 // test -- ok public class ContextInitListener
implements ServletContextListener { private static Logger logger = Logger.getLogger(ContextInitListener.class); // web項目通常來說,一般來說相對路徑是在/WEB-INF目錄下 private static final String BUSINESS_LOGIC_CONFIG_FILE_NAME = "business_logic.properties"; // 業務邏輯的配置文件名 @Override public void contextDestroyed(ServletContextEvent arg0) {
logger.info("自定義加載配置文件監聽器銷毀!"); } @Override public void contextInitialized(ServletContextEvent contextEvent) { logger.info("自定義加載配置文件監聽器初始化!"); // 1.裝載配置文件 Map<String, String> configsMap = this.loadBusinessLogicConfig(contextEvent); // 2.將配置加載到內存中Application this.loadConfigToApplication(contextEvent, configsMap); logger.info("自定義加載配置文件監聽器初始化!完成!"); } // 裝載配置文件 private Map<String, String> loadBusinessLogicConfig(ServletContextEvent contextEvent) { logger.info("開始裝載配置文件!"); // 加載配置文件 Properties props = new Properties(); try { String web_inf = contextEvent.getServletContext().getRealPath("/WEB-INF"); // 防止轉義 String loadPath = web_inf + "//" + BUSINESS_LOGIC_CONFIG_FILE_NAME; logger.info("加載配置文件路徑:" + loadPath); props.load(new FileInputStream(loadPath)); } catch (Exception ex) { logger.error("加載配置文件失敗!!!!"); return null; } // 解析配置文件 Map<String, String> map = new HashMap<String, String>((Map) props); logger.info("開始裝載配置文件!完成!"); return map; } // 將配置加載到內存中Application private void loadConfigToApplication(ServletContextEvent contextEvent, Map<String, String> configsMap) { logger.info("開始寫入配置到內存中!"); if (configsMap == null) { logger.error("配置參數為null,寫入失敗!!!"); return; } // 將配置文件裏的值裝入context屬性,這樣可以在JSP,SERVLET裏調用 ServletContext context = contextEvent.getServletContext(); for (Entry<String, String> entry : configsMap.entrySet()) { logger.info("寫入的key:" + entry.getKey() + " value:" + entry.getValue()); context.setAttribute(entry.getKey(), entry.getValue()); } logger.info("開始寫入配置到內存中!完成!"); } }

3.Spring中使用:

WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext(); ServletContext servletContext = webApplicationContext.getServletContext(); logger.info("info獲取請求:用戶登錄方法執行!"+ servletContext.getAttribute("sm2_sign_ip"));

web 中加載配置文件