监听器_是否启动web容器

来源:互联网 发布:手机炒股软件大全 编辑:程序博客网 时间:2024/06/04 18:56
在服务器启动前作判断。
 有某些项目当中,可能会出现需要先判断系统数据库或条件是否通过。如果通过就启动web容器,不通过就不启动web容器。
 以下给出解决思想:
  首先使用ServletContextListener接口作出判断(ServletContextListener会在容器启动前先执行) 
     在ServletContextListner中有两个方法。其中contextDestroyed是在服务器关闭时执行的方法,其中contextInitialized会在服务器启动前执行的方法。
  我们可以在contextInitialized中作判断,当需要停止web服务器时。我们可以调用System.exit(1)强制跳出系统停止服务器启动
    具体代码
package com.im.listener;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.log4j.Logger;
import org.hibernate.util.ConfigHelper;

import com.im.hibernate.HibernateSessionFactory;

public class SystemListener implements ServletContextListener {

public void contextDestroyed(ServletContextEvent arg0) {


}
public void contextInitialized(ServletContextEvent arg0) {
Logger logger=Logger.getLogger(SystemListener.class);
logger.info("系统数据库监听中");
Connection connection = null;
String url=HibernateSessionFactory.getConfiguration().getProperty("connection.url");
String user=HibernateSessionFactory.getConfiguration().getProperty("connection.username");
String password=HibernateSessionFactory.getConfiguration().getProperty("connection.password");
String connectionClass=HibernateSessionFactory.getConfiguration().getProperty("connection.driver_class");
try {
Class.forName(connectionClass);
connection=DriverManager.getConnection(url, user, password);
logger.info("系统数据库连接成功");
} catch (SQLException e) {
logger.error("系统数据库连接失败,停止启动服务器");
System.exit(1);
} catch (ClassNotFoundException e) {
logger.error("找不到系统数据库连接包,停止启动服务器");
System.exit(1);
}finally{
try {
if(connection!=null){
connection.close();
}
} catch (SQLException e) {
System.exit(1);
}
}
}

}


web.xml配置:
//添加服务器监听
<listener>
<listener-class>CheckDB</listener-class>
</listener>
0 0