当ServletContextListener#contextInitialized()失败时该怎么办

时间:2014-10-28 15:59:36

标签: java jsp tomcat servlets

如果假设我在ServletContextListener#contextInitialized()中初始化数据源为:

package com.myapp.listeners;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;

public class MyAppListener implements ServletContextListener {
    @Override
    public void contextDestroyed(ServletContextEvent event) {
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        try{
            InitialContext initialContext = new InitialContext();

            DataSource dataSource = (DataSource) initialContext.lookup("jdbc/myDB");

            event.getServletContext().setAttribute("datasource", dataSource);
        }catch(NamingException ne){
            // TODO WHAT TO DO HERE?
        }
    }
}

那么,如果初始化数据源失败了怎么办?如何阻止Tomcat部署此应用程序,因为没有数据源我没有部署应用程序的意义。

1 个答案:

答案 0 :(得分:3)

数据源应该可以从JNDI查找中获得,而不是像这样。我建议你将这个代码包装在一个方法中,而不是从ServletContext中检索它。

问题:如果初始化数据源失败了怎么办?如何阻止Tomcat部署此应用程序?

RuntimeException中抛出自定义contextInitialized,并且不会部署该应用程序。


从数据源检索连接:

//no need to extend from this class
public final class ConnectionProvider {
    private static final String DEFAULT_DS = "jdbc/myDB";
    //no need to initialize this class
    private ConnectionProvider() {
    }
    //retrieve the connection
    public static Connection getConnection() {
        Connection con = null;
        try {
            InitialContext initialContext = new InitialContext();
            DataSource dataSource = (DataSource) initialContext.lookup(DEFAULT_DS);
            con = dataSource.getConnection();
        } catch (Exception e) {
            //handle exception
            //basic handling, you should at least use a logger
            e.printStackTrace();
        }
        return con;
    }
}

然后在Service类中调用此静态方法(不在Servlet中,而不是在Dao中)。