Configuring JNDI datasource in Tomcat 6
I was starting on a new project yesterday and I needed the MySQL connection to be configured as a JNDI datasource on Tomcat 6. Tomcat 6 has a separate Web page detailing the steps required to configure JNDI datasource.
So following that advice, I copied the MySQL connection java driver (mysql-connector-java-3.0.17-ga-bin.jar) to TOMCAT_HOME/lib and then added the required entries in server.xml and web.xml as given below. Here xpc is the MySQL database instance I want to connect.
server.xml entry (under Context section)
<resource name="jdbc/xpc" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/xpc?autoReconnect=true"/>web.xml entry
<resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/xpc</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
Then I wrote sample code to connect to MySQL and select a value from a test table. The code is given below. In this sample, JSP calls the Test class to print the value of temp_val from test table. This code also demonstrates how to connect to a MySQL database using JNDI lookup.
Test.java
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class Test { public static String t() { try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/xpc"); Connection connection = ds.getConnection(); Statement stmt = connection.createStatement(); ResultSet resultSet = stmt.executeQuery("select * from test"); while (resultSet.next()) { String temp_val = resultSet.getString("temp_val"); return temp_val; } } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return null; } }
Test.jsp
<html> <body> <%=Test.t()%> </body>