myEclipse 8.5下的Tomcat 配置数据源

MyElipse 8.5 Tomcat 6 数据源配置

 

今天接触到了数据源(DataSource)和连接池,自己动手弄了一下。

 

首先说下我的运行环境

Ø        Jdk 1.6

Ø        Windows 7 旗舰盗版

Ø        MyEclipse 8.5(自带的tommac 6.x

Ø        MyEclipse 8.5的工作目录F:\Workspaces\MyEclipse 8.5,工程名为Test

 

很多东西都不知道,尤其是JNDI,所以Google和百度好久,总算弄出来

期间遇到诸多问题,与大家分享一下:

 

第一步:

先找到F:\Workspaces\MyEclipse 8.5\.metadata\.me_tcat\conf目录下的server.xml文件,打开,添加下面红色部分

   <!--Define the default virtual host

           Note: XML Schema validation will notwork with Xerces 2.2.

       -->

      <Host name="localhost"  appBase="webapps"

           unpackWARs="true" autoDeploy="true"

           xmlValidation="false" xmlNamespaceAware="false">

 

        <!-- SingleSignOn valve, share authentication between web applications

             Documentation at:/docs/config/valve.html -->

        <!--

        <ValveclassName="org.apache.catalina.authenticator.SingleSignOn" />

        -->

 

        <!-- Access log processes all example.

             Documentation at:/docs/config/valve.html -->

        <!--

        <ValveclassName="org.apache.catalina.valves.AccessLogValve"directory="logs" 

              prefix="localhost_access_log." suffix=".txt"pattern="common" resolveHosts="false"/>

        -->

           <!--配置数据源-->

           <Contextpath="/Test" docBase="F:\Workspaces\MyEclipse8.5\Test\WebRoot" debug="0" reloadable="true">

              <!—-要与web.xml中保持一致-->

              <Resourcename="jdbc/TestDB_1"

                       auth="Container"

                       type="javax.sql.DataSource"

                       factory="org.apache.commons.dbcp.BasicDataSourceFactory"

                       maxActive="100"

                       maxIdle="30"

                       maxWait ="10000"

                       username="root"

                       password="root"

                       driverClassName="com.mysql.jdbc.Driver"

                       url="jdbc:mysql://localhost:3306/gg_homepage?characterEncoding=UTF-8"/>

          

           </Context>

     </Host>

 

然后打开F:\Workspaces\MyEclipse8.5\Test\WebRoot\WEB-INF目录下的web.xml添加红色部分(注意这里是工程下的web.xml  而不是Tomcat下的

<servlet>

       <servlet-name>TestJDNIservlet</servlet-name>

       <servlet-class>com.test.jdni.TestJDNIservlet</servlet-class>

    </servlet>

    <servlet-mapping>

       <servlet-name>TestJDNIservlet</servlet-name>

       <url-pattern>/testJDNI</url-pattern>

    </servlet-mapping>

    <!-- 管理JDNI Resource -->

    <resource-ref>

       <description>DBConnection</description>

       <!—注意这里与server.xml中的要一致-->

       <res-ref-name>jdbc/TestDB_1</res-ref-name>        <res-type>javax.sql.DataSource</res-type>

       <res-auth>Container</res-auth>

    </resource-ref>

   

第二步:

创建一个servelet测试,配置信息上面已给出

package com.test.jdni;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.Statement;

 

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.sql.DataSource;

/**

 *

 * @project Test

 * @package com.test.jdni

 * @className TestJDNIservlet

 * @descriptionTODO(简要描述此类的用途)

 *    测试myElipse8.5 Tomcat配置数据源是否成功

 *    读取数据库内容并显示

 * @author Gaogao

 * @date 2012-5-7 上午10:56:55

 * 修改者

 * 修改时间

 * 修改备注 

 * @version v1.0

 */

publicclass TestJDNIservlet extends HttpServlet{

 

   /**

    * @fieldserialVersionUID:long TODO(简要说明其用途)

    */

   privatestaticfinallongserialVersionUID = 1L;

  

   private Connection con = null;

   private Statement stmt = null;

   private ResultSet rs = null;

  

  

   @Override

   protectedvoid service(HttpServletRequest req, HttpServletResponse res)

         throws ServletException, IOException {

      // TODO Auto-generatedmethod stub

      res.setContentType("text/html;charset=utf-8");

      StringBuilder result = new StringBuilder();

      try{

         //这些网上都有,自己谷歌百度

         Context ctx = new InitialContext();

         DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/TestDB_1");

         con = ds.getConnection();

         stmt = con.createStatement();

         rs = stmt.executeQuery("select user_id fromuser_info");

         while(rs.next()){

            result.append(rs.getString("user_id"));

            result.append("<br/>");

         }

      }catch(Exception e){

         e.printStackTrace();

      }finally{

         close();

      }

      PrintWriter out = res.getWriter();

      out.write(result.toString());

      out.flush();

      out.close();

     

   }

  

   /**

    *

    * @method close

    * @descriptionTODO(简要描述其功能)

    *   关闭数据库连接

    * @return void

    * @throws

    *     Exception(测试)

    * 修改者

    * 修改时间

    * 修改备注

    */

   publicvoid close(){

      if(rs != null){

         try{

            rs.close();

         }catch(Exception e1){

            e1.printStackTrace();

         }

      }

      if(stmt != null){

         try{

            stmt.close();

         }catch(Exception e2){

            e2.printStackTrace();

         }

      }

      if(con != null){

         try{

            con.close();

         }catch(Exception e3){

            e3.printStackTrace();

         }

      }

   }

}

 

第三步:

 好吧~开始测试….启动myElipse 8.5 中的Tomcat

Web Browser中输入http://localhost:8080/Test/testJNDI然后回车...

爆异常了

 

信息: Server startup in 425 ms

javax.naming.NamingException: Could not load resource factory class [Root exceptionis java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSourceFactory]

    at org.apache.naming.factory.ResourceFactory.getObjectInstance(ResourceFactory.java:81)

    atjavax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:304)

……..

Caused by: java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSourceFactory

    atorg.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1358)

 

Google+百度引入commons-dbcp.jar包解决

 

重新启动Tomcat  又爆异常了...

012-5-7 15:41:48org.apache.tomcat.util.modeler.Registry registerComponent

严重: Null componentCatalina:type=JspMonitor,name=jsp,WebModule=//localhost/Test,J2EEApplication=none,J2EEServer=none

java.lang.reflect.InvocationTargetException

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

    at java.lang.reflect.Method.invoke(Method.java:597)

    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)

    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)

Caused by:java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool

    atorg.apache.commons.dbcp.BasicDataSourceFactory.createDataSource(BasicDataSourceFactory.java:156)

    atorg.apache.commons.dbcp.BasicDataSourceFactory.getObjectInstance(BasicDataSourceFactory.java:145)

 

好吧~又少jar包了加入commons-pool-1.5.6.jar解决

 

再次重启服务器,http://localhost:8080/Test/testJNDI执行哦喝!

信息: Server startup in 435 ms

org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'

    at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1136)

    at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)

    at com.test.jdni.TestJDNIservlet.service(TestJDNIservlet.java:52)

    at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

    atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)

    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)

    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)

    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)

    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)

    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)

    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)

    atorg.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)

    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)

    at java.lang.Thread.run(Thread.java:619)

Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

    atorg.apache.catalina.loader.WebappClassLoader.loadClass(Weba

 

加入jarmysql-connector-java-5.1.5-bin.jar 解决

 

说明一下所有jar包都加在F:\Workspaces\MyEclipse8.5\Test\WebRoot\WEB-INF\lib目录

 

再次运行,得到预期结果

1
1234567
12345678
123rr
123test
cccccccc
gaaaaaaa
一部分数据


遗留问题

 

修改server.xml中信息如下红色部分

<!--配置数据源-->

           <Context path="/Test"docBase="F:\Workspaces\MyEclipse 8.5\Test\WebRoot"debug="0" reloadable="true">

              <!--第一种方式-->

              <!--<Resourcename="jdbc/TestDB_1"

                      auth="Container"

                      type="javax.sql.DataSource"

                      factory="org.apache.commons.dbcp.BasicDataSourceFactory"

                      maxActive="100"

                      maxIdle="30"

                       maxWait="10000"

                      username="root"

                      password="root"

                      driverClassName="com.mysql.jdbc.Driver"

                      url="jdbc:mysql://localhost:3306/gg_homepage?characterEncoding=UTF-8"/>-->

           <!--第二种方式-->        

           <Resource name="jdbc/TestDB_1"

                       auth="Container"

                       type="javax.sql.DataSource"/>

           <ResourceParams name="jdbc/TestDB_1">

                  <parameter>

                     <name>factory</name>

                     <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>

                  </parameter>

                  <!-- Maximum number of dB connections in pool.Make sure you configure your mysqld max_connections large enough to handle allof your db connections. Set to 0 for no limit.

                  -->

                  <parameter>

                     <name>maxActive</name>

                     <value>100</value>

                  </parameter>

 

 

                  <!-- Maximum number of idle dB connections toretain in pool.

                  Set to 0 for no limit.

                  -->

                  <parameter>

                     <name>maxIdle</name>

                     <value>30</value>

                  </parameter>

 

 

                  <!-- Maximum time to wait for a dB connection tobecome available in ms, in this example 10 seconds. An Exception is thrown ifthis timeout is exceeded.   Set to -1 towait indefinitely.

                  Maximum time to wait for a dB connection to becomeavailable in ms, in this example 10 seconds. An Exception is thrown if thistimeout is exceeded.    Set to -1 to waitindefinitely.

                  -->

                  <parameter>

                     <name>maxWait</name>

                     <value>10000</value>

                  </parameter>

 

 

                  <!-- DB username and password for dB connections -->

                  <parameter>

                     <name>username</name>

                     <value>root</value>

                  </parameter>

                  <parameter>

                     <name>password</name>

                     <value>root</value>

                  </parameter>

 

 

                  <!-- Class name for JDBC driver -->

                  <parameter>

                     <name>driverClassName</name>

                     <value>com.mysql.jdbc.Driver</value>

                  </parameter>

 

 

                  <!-- The JDBC connection url for connecting toyour DB.-->

                  <parameter>

                     <name>url</name>

                      <value>jdbc:mysql://localhost:3306/gg_homepage?characterEncoding=UTF-8</value>

                  </parameter>

              </ResourceParams>-->

           </Context>

 

爆了这个异常

信息: Server startup in 463 ms

org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL'null'

    at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1150)

    at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)

    at com.test.jdni.TestJDNIservlet.service(TestJDNIservlet.java:52)

    at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

    atorg.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)

    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)

    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)

    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)

    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)

    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)

    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)

    atorg.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)

    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)

    at java.lang.Thread.run(Thread.java:619)

Caused by: java.lang.NullPointerException

    at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(JdbcOdbcDriver.java:507)

    atsun.jdbc.odbc.JdbcOdbcDriver.knownURL(JdbcOdbcDriver.java:476)

 

 

请问大虾们这是为什么? 2种方式的区别?

 

 

 

再苦再累,也要坚持!

:

如果报Cannotcreate PoolableConnectionFactory (Access denied for user ''@'localhost' (usingpassword: NO))异常

请检查usernamepassword 是否写错~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值