java - 如何将自己的连接池的初始化放在struts-config.xml中?

标签 java servlets struts connection-pooling struts-config

我有自己的连接池类

public class ConnectionPool {


private static final Logger log = Logger.getLogger(ConnectionPool.class);

public final static String PROPERTIES_FILENAME = "config";
public static final int DEFAULT_POOL_SIZE = 10;


//single instance
private static ConnectionPool instatance;
//queue of free connections
private BlockingQueue<Connection> connectionQueue;

public ConnectionPool(String driver, String url, String user,
        String password, int poolSize)
        throws ClassNotFoundException, DAOException{
    try{
        Class.forName(driver);
        connectionQueue = new ArrayBlockingQueue<Connection>(poolSize);
        for(int i = 0; i < poolSize ;i++){
            Connection connection = DriverManager.getConnection(url, user, password);
            connectionQueue.offer(connection);
        }
    }
    catch (SQLException e) {
        log.error(e);
        throw new DAOException(e.getMessage());
    }
}

public static void init() throws DAOException{
    try {
    if(instatance == null){


        String driver  =  ConfigurationManager.
        getInstance().getProperty("DATABASE_DRIVER_NAME");
        String url = ConfigurationManager.
        getInstance().getProperty("DATABASE_URL");
        String user = ConfigurationManager.
        getInstance().getProperty("DATABASE_USER");
        String password = ConfigurationManager.
        getInstance().getProperty("DATABASE_PASSWORD");
        String poolSizeStr = ConfigurationManager.
        getInstance().getProperty("DATABASE_POOLSIZE");
        int poolSize = (poolSizeStr != null) ?
                Integer.parseInt(poolSizeStr) : DEFAULT_POOL_SIZE;

        log.info("Trying to create pool of connections...");

        instatance = new ConnectionPool(driver,url,user,password,poolSize);

        log.info("Connection pool initialized");
    }
    }catch (ClassNotFoundException e) {
        log.error(e);
    } catch (SQLException e) {
        log.error(e);
        throw new DAOException(e.getMessage());
    }
}

public static void dispose() throws DAOException {
    try {
        if(instatance != null){
            instatance.clearConnectionQueue();
            instatance = null;
            log.info("Connection queue is disposed");
        }
    } catch (DAOException e) {
        log.info(e.getMessage());
        throw new DAOException(e.getMessage());
    }
}

public static ConnectionPool getInstance(){
    return instatance;
}

public Connection takeConnection() {
    Connection connection = null;
    try{
        connection = connectionQueue.take();
    }catch (InterruptedException e) {
        log.info("Free connection waiting interrupted.Returned null connection");
        log.error(e);
    }
    return connection;
}

public void releaseConnection(Connection connection) throws DAOException {
    try {

        if(!connection.isClosed()){
            if(!connectionQueue.offer(connection)){
                log.info("Connections is not added.");
            }
        }
        else{
            log.info("Trying to release closed connection.");
        }
    } catch (SQLException e) {
        log.info("SQLException at connection isClosed(). Connection is not added");
        throw new DAOException(e.getMessage());
    }
}

private void clearConnectionQueue() throws DAOException{
    try {
        Connection connection;
        while((connection = connectionQueue.poll()) != null){

            if(!connection.getAutoCommit()){
                connection.commit();
                connection.close();
            }
    }
    } catch (SQLException e) {
        log.info(e.getMessage());
        throw new DAOException(e.getMessage());
    }
}

并需要在 struts servlet 生命周期开始时对其进行初始化。如果它是常规 servlet,我会不假思索地使用 init() 方法,并且我会这样做:

public class LinkAction extends DispatchAction {
private static final String PARAM_NAME_LANGUAGE = "language";

/**
 * This is the Struts action method called on
 * http://.../actionPath?method=myAction1,
 * where "method" is the value specified in <action> element : 
 * ( <action parameter="method" .../> )
 */
private static ConnectionPool connectionPool =
    ConnectionPool.getInstance();

public void init(){
    try {
        if(connectionPool == null){

            ConnectionPool.init();
            connectionPool = ConnectionPool.getInstance();
        }

    } catch (DAOException e) {
        log.error(e);
    }
}


public ActionForward newsList(ActionMapping mapping, ActionForm  form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    return mapping.findForward("newsList");
}

public ActionForward addNews(ActionMapping mapping, ActionForm  form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    return mapping.findForward("addNews");
}

public ActionForward changeLocale(ActionMapping mapping, ActionForm  form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String localeValue = request.getParameter("localeValue");
    request.getSession().setAttribute(PARAM_NAME_LANGUAGE, localeValue);
    return mapping.findForward("newsList");
}


}

但这不适用于 Struts Action,因此我决定可以在 struts-config.xmlweb.xml 中完成。但如何呢?

最佳答案

我认为你应该使用 ServletContextListener:

http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html

即使使用其他框架,它也是放置数据源初始化代码的好地方。 每次应用程序启动并运行时都会调用此监听器,以便您可以将数据源放入上下文属性中并在必要时恢复它。

关于java - 如何将自己的连接池的初始化放在struts-config.xml中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10453285/

相关文章:

java - 使显示标签隐藏

javascript - Console.log 和 Alert 在 Chrome 中不起作用

java - Servlet 方法没有被调用?

java - Jquery Ajax调用servlet不成功

java - Tomcat 应用程序和存储在数据库中的全局变量。用于维护服务器和应用程序的管理器应用程序

java - 调试一个简单的 Java 控制台游戏

java - 使用显示标签 1.1.1 将数据导出到 Excel 时出错

java - 使用 gzip 压缩组件 - Java EE

java - Android - Java 中的类序列

struts - struts1 中的 org.apache.jasper.JasperException