tomcat的JNDI数据源绑定

tomcatJNDI数据源绑定

jsp开发中调用tomcat数据库连接池,可能很多朋友都会,下面这段代码相信用过的人都很熟悉:

list1testpool.jsp

<%

InitialContext ctx=new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();

String strSql = " select * from t_user";
ResultSet rs = stmt.executeQuery(strSql);
......
stmt.close();
rs.close();
conn.close();

%>

但是许多人不知tomcat启动时,用jndi对数据源做了绑定,所以就不知道如何在j2se中用main函数调用这个数据源,其实,只要把testpool.jsp做一点改动:

InitialContext ctx=new InitialContext();
Object o = ctx.lookup("java:comp/env/hibernate");
out.print(" o.getClass().getName());
DataSource ds=(DataSource)o;
.......

即利用反射API打印出这个已注册到jndi中数据源对象的class全名,就会知道原来数据源是一个 “org.apache.commons.dbcp.BasicDataSource”对象,这个class就在%Tomcat%commonlib commons-dbcp-1.2.1.jar包里,与其关联的还有commons-collections-3.1.jarcommons- pool-1.2.jar

把以上三个包加入当前的工作环境,用下面这段代码就可调用连接池了。我用的是mysql数据库,请在调试时加入mysqljdbc驱动%Tomcat%commonlib下的naming-common.jar

 

         public static void main(String[] args) {

                   try{

                            BasicDataSource bds = new BasicDataSource();

                           

                            //设置数据库驱动

                            bds.setDriverClassName("com.mysql.jdbc.Driver");

                            //设置JDBCURL

                            bds.setUrl("jdbc:mysql://localhost:3306/webqq");

                            bds.setUsername("root");

                            bds.setPassword("root");

                            //设置连接池初始大小

                            bds.setInitialSize(2);

 

                            //JNDI配置

                            Hashtable<String, String> env = new Hashtable<String, String>();

                            env.put("java.naming.factory.initial","org.apache.naming.java.javaURLContextFactory");

                            InitialContext ctx=new InitialContext(env);

 

                            //数据源绑定到JNDI

                            ctx.bind("tomcatDS",bds);

                            //JNDI查找数据源

                            DataSource ds = (DataSource)ctx.lookup("tomcatDS");

 

                            Connection con = ds.getConnection();

                            Statement stmt = con.createStatement();

                            String strSql = "select * from user";

                            ResultSet rs = stmt.executeQuery(strSql);

                            while(rs.next()){

                                     System.out.println("id="+rs.getString(1));

                            }

                            rs.close();

                            stmt.close();

                            con.close();

                   }catch(Exception ex){

                            System.out.print(ex.toString());

                   }

 

         }

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页