web 中加载配置文件
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"
));