论坛首页 入门讨论版 Java

在服务器启动前作条件判断

浏览 115 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
最后更新时间:2008-08-07
在服务器启动前作判断。
 有某些项目当中,可能会出现需要先判断系统数据库或条件是否通过。如果通过就启动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);
			}
		}
	}

}

//添加服务器监听
<listener>
	 <listener-class>CheckDB</listener-class>
</listener>
   
最后更新时间:2008-08-07
希望能给大家带来一点点的帮助
   
0 请登录后投票
论坛首页 入门讨论版 Java

跳转论坛:
JavaEye推荐