JNDI(Java 命名和目录接口)(六)(附2)

 0. Introduction
Versions of MySQL and the mm.mysql JDBC driver when have been reported to work:

MySQL 3.23.47, MySQL 3.23.47 using InnoDB, MySQL 4.0.1alpha
mm.mysql 2.0.14 (JDBC Driver)
Please let us know if you have tested the new MySQL mm.mysql 3.0 driver.

1. MySQL configuration
Ensure that you follow these instructions as variations can cause problems.

Create a new test user, a new database and a single test table. Your MySQL user must have a password assigned. The driver will fail if you try to connect with an empty password.

   
mysql>; GRANT ALL PRIVILEGES ON *.* TO javauser@localhost
    ->;   IDENTIFIED BY 'javadude' WITH GRANT OPTION;
mysql>; create database javatest;
mysql>; use javatest;
mysql>; create table testdata (
    ->;   id int not null auto_increment primary key,
    ->;   foo varchar(25),
    ->;   bar int);

  
   

Note: the above user should be removed once testing is complete!

Next insert some test data into the testdata table.

   
mysql>; insert into testdata values(null, 'hello', 12345);
Query OK, 1 row affected (0.00 sec)

mysql>; select * from testdata;
+----+-------+-------+
| ID | FOO   | BAR   |
+----+-------+-------+
|  1 | hello | 12345 |
+----+-------+-------+
1 row in set (0.00 sec)

mysql>;

  
   


2. server.xml configuration
Configure the JNDI DataSource in Tomcat by adding a declaration for your resource to $CATALINA_HOME/conf/server.xml.

Add this in between the </Context>; tag of the examples context and the </Host>; tag closing the localhost definition.

   
<Context path="/DBTest" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true">;

  <Logger className="org.apache.catalina.logger.FileLogger"
             prefix="localhost_DBTest_log." suffix=".txt"
             timestamp="true"/>;

  <Resource name="jdbc/TestDB"
               auth="Container"
               type="javax.sql.DataSource"/>;

  <ResourceParams name="jdbc/TestDB">;
    <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
         all of your db connections. Set to 0 for no limit.
         -->;
    <parameter>;
      <name>;maxActive</name>;
      <value>;100</value>;
    </parameter>;

    <!-- Maximum number of idle dB connections to retain in pool.
         Set to 0 for no limit.
         -->;
    <parameter>;
      <name>;maxIdle</name>;
      <value>;30</value>;
    </parameter>;

    <!-- Maximum time to wait for a dB connection to become available
         in ms, in this example 10 seconds. An Exception is thrown if
         this timeout is exceeded.  Set to -1 to wait indefinitely.
         -->;
    <parameter>;
      <name>;maxWait</name>;
      <value>;10000</value>;
    </parameter>;

    <!-- MySQL dB username and password for dB connections  -->;
    <parameter>;
     <name>;username</name>;
     <value>;javauser</value>;
    </parameter>;
    <parameter>;
     <name>;password</name>;
     <value>;javadude</value>;
    </parameter>;

    <!-- Class name for mm.mysql JDBC driver -->;
    <parameter>;
       <name>;driverClassName</name>;
       <value>;org.gjt.mm.mysql.Driver</value>;
    </parameter>;

    <!-- The JDBC connection url for connecting to your MySQL dB.
         The autoReconnect=true argument to the url makes sure that the
         mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
         connection.  mysqld by default closes idle connections after 8 hours.
         -->;
    <parameter>;
      <name>;url</name>;
      <value>;jdbc:mysql://localhost:3306/javatest?autoReconnect=true</value>;
    </parameter>;
  </ResourceParams>;
</Context>;

  
   


3. web.xml configuration
Now create a WEB-INF/web.xml for this test application.

   
<?xml version="1.0" encoding="ISO-8859-1"?>;
    <!DOCTYPE web-app PUBLIC
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">;
<web-app>;
  <description>;MySQL Test App</description>;
  <resource-ref>;
      <description>;DB Connection</description>;
      <res-ref-name>;jdbc/TestDB</res-ref-name>;
      <res-type>;javax.sql.DataSource</res-type>;
      <res-auth>;Container</res-auth>;
  </resource-ref>;
</web-app>;

  
   


4. Test code
Now create a simple test.jsp for use later.

   
<html>;
  <head>;
    <title>;DB Test</title>;
  </head>;
  <body>;

  <%
    foo.DBTest tst = new foo.DBTest();
    tst.init();
  %>;

  <h2>;Results</h2>;
    Foo <%= tst.getFoo() %>;<br/>;
    Bar <%= tst.getBar() %>;

  </body>;
</html>;

  
   


And create a Java class to actually use your new Datasource and connection pool. Note: this code isn't anywhere near production ready - it's only supposed to be used as a simple test :-)

   
package foo;

import javax.naming.*;
import javax.sql.*;
import java.sql.*;

public class DBTest {

  String foo = "Not Connected";
  int bar = -1;
   
  public void init() {
    try{
      Context ctx = new InitialContext();
      if(ctx == null )
          throw new Exception("Boom - No Context");

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

      if (ds != null) {
        Connection conn = ds.getConnection();
              
        if(conn != null)  {
            foo = "Got Connection "+conn.toString();
            Statement stmt = conn.createStatement();
            ResultSet rst =
                stmt.executeQuery(
                  "select id, foo, bar from testdata");
            if(rst.next()) {
               foo=rst.getString(2);
               bar=rst.getInt(3);
            }
            conn.close();
        }
      }
    }catch(Exception e) {
      e.printStackTrace();
    }
}

public String getFoo() { return foo; }
public int getBar() { return bar;}
}

  
   


Finally deploy your web app into $CATALINA_HOME/webapps either as a warfile called DBTest.war or into a sub-directory called DBTest

Once deployed, point a browser at http://localhost:8080/DBTest/test.jsp to view the fruits of your hard work.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值