Vous êtes sur la page 1sur 5

27.3.4.2.

Using Connector/J with Tomcat

The following instructions are based on the instructions for Tomcat-5.x, available at
http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.html which is
current at the time this document was written.

First, install the .jar file that comes with Connector/J in $CATALINA_HOME/common/lib so that it
is available to all applications installed in the container.

Next, Configure the JNDI DataSource by adding a declaration resource to


$CATALINA_HOME/conf/server.xml in the context that defines your web application:

<Context ....>

...

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

<!-- The name you used above, must match _exactly_ here!

The connection pool will be bound into JNDI with the name
"java:/comp/env/jdbc/MySQLDB"
-->

<ResourceParams name="jdbc/MySQLDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>

<!-- Don't set this any higher than max_connections on your


MySQL server, usually this should be a 10 or a few 10's
of connections, not hundreds or thousands -->

<parameter>
<name>maxActive</name>
<value>10</value>
</parameter>

<!-- You don't want to many idle connections hanging around


if you can avoid it, only enough to soak up a spike in
the load -->

<parameter>
<name>maxIdle</name>
<value>5</value>
</parameter>

<!-- Don't use autoReconnect=true, it's going away eventually


and it's a crutch for older connection pools that couldn't
test connections. You need to decide whether your application is
supposed to deal with SQLExceptions (hint, it should), and
how much of a performance penalty you're willing to pay
to ensure 'freshness' of the connection -->

<parameter>
<name>validationQuery</name>
<value>SELECT 1</value>
</parameter>
<!-- The most conservative approach is to test connections
before they're given to your application. For most applications
this is okay, the query used above is very small and takes
no real server resources to process, other than the time used
to traverse the network.

If you have a high-load application you'll need to rely on


something else. -->

<parameter>
<name>testOnBorrow</name>
<value>true</value>
</parameter>

<!-- Otherwise, or in addition to testOnBorrow, you can test


while connections are sitting idle -->

<parameter>
<name>testWhileIdle</name>
<value>true</value>
</parameter>

<!-- You have to set this value, otherwise even though


you've asked connections to be tested while idle,
the idle evicter thread will never run -->

<parameter>
<name>timeBetweenEvictionRunsMillis</name>
<value>10000</value>
</parameter>

<!-- Don't allow connections to hang out idle too long,


never longer than what wait_timeout is set to on the
server...A few minutes or even fraction of a minute
is sometimes okay here, it depends on your application
and how much spikey load it will see -->

<parameter>
<name>minEvictableIdleTimeMillis</name>
<value>60000</value>
</parameter>

<!-- Username and password used when connecting to MySQL -->

<parameter>
<name>username</name>
<value>someuser</value>
</parameter>

<parameter>
<name>password</name>
<value>somepass</value>
</parameter>

<!-- Class name for the Connector/J driver -->

<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>

<!-- The JDBC connection url for connecting to MySQL, notice


that if you want to pass any other MySQL-specific parameters
you should pass them here in the URL, setting them using the
parameter tags above will have no effect, you will also
need to use &amp; to separate parameter values as the
ampersand is a reserved character in XML -->

<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/test</value>
</parameter>

</ResourceParams>
</Context>

In general, you should follow the installation instructions that come with your version of Tomcat,
as the way you configure datasources in Tomcat changes from time-to-time, and unfortunately if
you use the wrong syntax in your XML file, you will most likely end up with an exception
similar to the following:

Error: java.sql.SQLException: Cannot load JDBC driver class 'null ' SQL
state: null
Previous / Next / Up / Table of Contents

User Comments
Posted by Al Hopper on November 18 2005 1:32pm [Delete] [Edit]

The above did not work for me with Tomcat 5.5.9, but the following did:

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


initialSizse="30" maxActive="100" maxIdle="30" maxWait="10000"
username="my_user" password="my_password" driverClassName="com.mysql.jdbc.Driver"
removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true"
url="jdbc:mysql://localhost:3306/my_databasename"/>

Posted by Benjamin Slade on November 10 2005 1:29pm [Delete] [Edit]

server.xml is the old location for the <Context> but these days it's usually found either in
conf/Catalina/[hostname]/[appname].xml or in webapps/[appname]/META-INF/context.xml.

Also note that the syntax of <Resource> has changed in 5.5. See
http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html

Posted by Benjamin Slade on November 12 2005 10:39pm [Delete] [Edit]

Note, the <ResourceParams> tag used in the above example is no longer valid Tomcat 5.5; it's
still OK for tomcat 5.0 and lower.

The example above is not useful to newbies for several reasons. It assumes a newbie already
understands the concept of declaring a resource within a context for a web application. It also
assumes that the newbie wants to declare this database connection resource to be global across
all web applications in this Tomcat installation, but doesn't say that.
Here's what worked for me.

I created a file $CATALINA_HOME/webapps/MyApps/META-INF/context.xml where


$CATALINA_HOME is the installation directory for Tomcat and MyApps is the web application
directory where you're gonna put a bunch of related JSP files sharing the database connection
info specified in the context.xml file.

I then added the following for the content of context.xml (from <Context> to </Context> tag):

<Context reloadable="true" >

<Resource name="jdbc/TestDB" auth="Container"


type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="test_mysql_login"
password="test_mysql_password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/javatest?autoReconnect=true"
/>

</Context>

Next I placed the following into a .jsp file in the MyApps directory:

<%@ page
import="java.sql.*"
import="java.util.*"
import="java.io.*"
import="org.apache.commons.dbcp.*"
import ="org.apache.commons.pool.*"
import="org.apache.commons.pool.impl.*"
import="javax.naming.*"
import="javax.sql.*"
%>
<%
DataSource ds=null;
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");
ds=(DataSource)ctx.lookup("java:comp/env/jdbc/TestDB");
if(ds == null )
throw new Exception("Boom - No Datasource");

Connection conn=ds.getConnection();
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select 'Hello World from MySQL'");
if (rs.next()){
%><%=rs.getString(1)%><%
}
%>

Note that "jdbc/TestDB" is the key string used to access the database connection resource info in
the context.xml file.

You can see my overly detailed writeup on installing Java, Tomcat, and MySQL into an Mac OS
X environment (pretty close to generic Unix) at the web address:
http://www.benslade.com/projects/java/tomcat/InstallingJavaTomcatMySQLOnMacOSX/

Ben Slade
PublicMailbox at BenSlade dot com

Posted by Al Hopper on November 18 2005 1:41pm [Delete] [Edit]

NB: AutoReconnect=true is deprecated. See changelog section 23.3.6. (go several pages forward
to the Changelog)

Add your own comment.

Vous aimerez peut-être aussi