公司框架学习之Listener《二》
一、功能
由<context-param>与<listener>两个标签实现加载数据库配置文件。
二、<context-param>作用
1. 启动一个WEB项目的时候,容器(如:Tomcat)会去读它的配置文件web.xml.读两个节点: <listener></listener> 和 <context-param></context-param>
2.紧接着,容器创建一个ServletContext(上下文),这个WEB项目所有部分都将共享这个上下文.
3.容器将<context-param></context-param>转化为键值对,并交给ServletContext.
4.容器创建<listener></listener>中的类实例,即创建监听.
5.在监听中会有contextInitialized(ServletContextEvent args)初始化方法,在这个方法中获得ServletContext = ServletContextEvent.getServletContext();
context-param的值 = ServletContext.getInitParameter("context-param的键");
context-param的值 = ServletContext.getInitParameter("context-param的键");
6.得到这个context-param的值之后,你就可以做一些操作了.注意,这个时候你的WEB项目还没有完全启动完成.这个动作会比所有的Servlet都要早.
换句话说,这个时候,你对<context-param>中的键值做的操作,将在你的WEB项目完全启动之前被执行.
换句话说,这个时候,你对<context-param>中的键值做的操作,将在你的WEB项目完全启动之前被执行.
7.举例.你可能想在项目启动之前就打开数据库.
那么这里就可以在<context-param>中设置数据库的连接方式,在监听类中初始化数据库的连接.
那么这里就可以在<context-param>中设置数据库的连接方式,在监听类中初始化数据库的连接.
8.web.xml
<context-param>
<param-name>data.path</param-name>
<!--数据库配置文件所在目录-->
<param-value>D:\eclipse-space\JMB\src\data</param-value>
</context-param>
三、<listener>与WebContextListener.java
1.web.xml
<listener>
<listener-class>com.feiwei.framework.web.listener.WebContextListener</listener-class>
</listener>
2.WebContextListener.java
package com.feiwei.framework.web.listener; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.logicalcobwebs.proxool.ProxoolFacade; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader; import com.feiwei.framework.cache.MemcachedUtils; import com.feiwei.framework.core.AppConfig; import com.feiwei.framework.core.TaskCenter; import com.feiwei.framework.dao.hibernate.SessionFactoryCenter; import com.feiwei.framework.util.HttpUtils; import com.feiwei.framework.util.Logs; import com.feiwei.framework.util.StringUtils; import com.feiwei.framework.util.ThreadUtils; import com.feiwei.framework.util.WebUtils; public class WebContextListener extends ContextLoader implements ServletContextListener { //容器开启时 public void contextInitialized(ServletContextEvent config) { ServletContext context = config.getServletContext(); //获取<context-param></context-param>标签中值 String path = context.getInitParameter("data.path"); String dataPath = path; System.out.println("获取data.path值:"+path); if (path != null) { //获取本机系统变量path的值 dataPath = System.getenv(path.substring(5)); } if (dataPath == null) { //获取绝对路径 dataPath = context.getRealPath("/WEB-INF/classes/data"); } //在本机上找不到该文件路径 if (!new File(dataPath).exists()) { String msg = "DATA目录路径无效,请检查配置。config=" + dataPath + "; path=" + path; Logs.error(msg); throw new RuntimeException(msg); } //为程序配置ip AppConfig.setServerIp(WebUtils.getServerIp()); //为程序配置tomcat端口 AppConfig.setServerPort(WebUtils.getServerPort()); //为程序配置tomcat环境变量 AppConfig.setTomcatBase(WebUtils.getTomcatBase()); //properties类加载config.propertis配置信息 AppConfig.init(dataPath); //将dataPath设置为程序系统的全局变量 System.setProperty("DataPath", dataPath); initStaticServer(); } //连接http://localhost静态资源无服务器 private void initStaticServer() { ThreadUtils.run(new Runnable() { public void run() { StringBuilder message = new StringBuilder(); message.append("正在连接静态资源服务器..... ");
//判断请求的状态码是否正常(200) if (HttpUtils.isOk(AppConfig.getStaticServer())) { message.append(" OK"); } else { message.append(" 失败"); } System.out.println(message); } }); } //容器关闭时 public void contextDestroyed(ServletContextEvent context) {
//结束所有线程 TaskCenter.destory();
//关闭数据库连接 ProxoolFacade.shutdown();
//关闭缓存 MemcachedUtils.clear();
//关闭servletContext closeWebApplicationContext(context.getServletContext()); } }
与WebContextListener.java相关的类:WebUtils.java(只展示相关方法)
public static String getServerIp() { try { //获取ip InetAddress addr = InetAddress.getLocalHost(); return addr.getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } return "127.0.0.1"; } //获取tomcat端口 public static String getServerPort() { String base = System.getProperty("catalina.base"); String serverXml = base + "/conf/server.xml"; try { Document doc = XMLUtils.fromXML(new FileReader(serverXml), "utf-8"); Element connector = (Element) doc.selectNodes("//Connector").get(0); return connector.attributeValue("port"); } catch (Exception e) { System.out.println(serverXml + " 配置文件读取tomcat端口错误!"); } return null; } //获取tomcat环境变量 public static String getTomcatBase() { String base = System.getProperty("catalina.base");if (StringUtils.isEmpty("base")) { throw new RuntimeException("catalina.base=" + base + " 配置环境变量读取错误!"); } return base; }
与WebContextListener.java相关类:AppConfig.java(只展示最关键方法)
private static Properties config = new Properties(); public static synchronized void init(String pdataPath) { dataPath = pdataPath; File configFile = new File(dataPath + "/config.properties"); try { //最后一次修改时间 Long modifyTime = Long.valueOf(configFile.lastModified()); if (lastModify != modifyTime.longValue()) { //将config.properties配置文件加载到Properties对象中 config.load(new FileInputStream(configFile)); lastModify = modifyTime.longValue(); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(dataPath + "/config.properties is not exist"); } }
config.properties
# 项目阶段,有如下三个阶段:develop:开发阶段;test:测试阶段;product:产品阶段(正式运行) app.state=develop # 系统的区域 app.region=50 # 分店代码 app.jgdm=500192100 #压缩CSS.JS pack.js.css=false #session 超时分钟 10小时 session.timeout=600 # cache server,多个memcached server通过逗号分隔 cache.server=127.0.0.1:11211 # 云中心服务器地址 cloud.host=localhost #静态服务器地址,提供资源和文件下载# static.server=http://localhost # Hession 代理是否启用 #/ hession.proxy=false # 数据库配置 多个分区服务器,用','隔开 #SYS数据库指向 datasource.sys=sys.xml #SYS数据库指向 datasource.ssss=ssss.xml #数据中心库指向 datasource.data=data.xml #日志库指向 datasource.log=log.xml #日志库指向 datasource.dsc=datasource.sys #JDBC SQL 日志输出 jdbclog.enable=true #存放附件指定的位置 sjtl.fjxx=//172.16.3.6/sjtlfj #数据交换配置 #Ftp服务器地址 ex.ftp.host=172.16.3.9:21 #Ftp用户名 ex.ftp.username=Anonymous #Ftp密码 ex.ftp.password= #本地临时目录,注意斜杠的写法 ex.temp=E:\\ex_temp #交换数据目录 ex.mdf=E:\\ex_mdf #交换数据目录 ex.data=E:\\upload
总结:按照之前开源框架搭建项目,spring配置文件中注册数据库信息,此项目spring配置中只有一个获取spring所有bean的SpringUtls工具类,无法得知如何去加载数据库连接信息的。
浙公网安备 33010602011771号