Setup Connection pooling in jsp/servlets applicati

2019-09-06 17:48发布

问题:

I want to use Connection pooling in my java web application with MySQL and JDBC, I found a very resource to learn at Apache Tomcat 6.0 (6.0.35) - JNDI Datasource HOW-TO, But this example uses JSTL code to explain how to retrieve connection from pool. I want to work similarly but with a MVC architecture from scratch consisting of Beans, DAOs, Servlets and JSPs. I got everything I want from a very good DAO tutorial by BalusC but I am confused in the last part of tutorial saying How about Connection Pooling?. Could anyone please elaborate on this connection pooling topic and the close() method?

EDIT:
Actually i should have add this thing earlier also:
As the tutorial I have linked above comes before JDK7, which now has try-wth-resource code that closes the Connection automatically, then how can we maintain a Connection pool and closing a Connection in pool here with the same DAO code (or with few changes) as in the tutorial?

回答1:

if your application requires is to be used by several users one connection can be held by a connection pool so several of those users will reuse the existing connection instead of making new connection which will consume time. about the close()method: the connection pool stays active and if you do not close a connection to it after every access,connections will pile up and if the number increases the connection pool get jammed and no longer accepts other connections!

public class MyDao {

    private InitialContext context;
    private DataSource datasource;

    public MyDao() {

        try {

            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
            context = new InitialContext();
            datasource = (DataSource) context.lookup("datasource name");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }

    }
 public MyBean getMyBean() throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet res = null;

        String sql = "some query";
        try {
            connection = datasource.getConnection();//pool connection
            statement = connection.prepareStatement(sql);
            res = statement.executeQuery();
            while (res.next()) {
               //return true

            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

     finally {
            if (rs!= null) try { rs.close(); } catch (SQLException logOrIgnore) {}//result set if any
            if (stm!= null) try { stm.close(); } catch (SQLException logOrIgnore) {}//clase statement if any
            if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}//close connection
            }
            }


}//close MyDao