基于Struts与Tomcat7的Java项目转JNDI连接池技术问询
Hey there! Let’s break down exactly what you need to do to switch from plain JDBC/ODBC to a JNDI connection pool in your Struts + Tomcat 7 project. I’ve tackled this transition multiple times, so I’ll walk you through each step clearly.
The biggest change here is replacing your manual JDBC connection setup with a JNDI lookup.
Before (Plain JDBC):
You probably have code like this scattered around your action classes or DAOs:
// Hardcoded DB credentials & driver setup Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/your_db", "username", "password" );
After (JNDI Connection Pool):
Replace that with code that fetches the pooled DataSource from Tomcat’s JNDI context:
try { // Get the initial context Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); // Look up your DataSource (name matches what you'll configure in Tomcat) DataSource ds = (DataSource) envCtx.lookup("jdbc/YourDBPool"); // Get a connection from the pool Connection conn = ds.getConnection(); // Use the connection as usual... } catch (NamingException | SQLException e) { // Handle exceptions appropriately (log, rethrow, etc.) e.printStackTrace(); }
A few key notes:
- No more hardcoded credentials: All DB config moves to Tomcat, making your code cleaner and more secure.
- Connection handling: When you call
conn.close(), you’re not actually closing the connection—you’re returning it to the pool for reuse. Keep using try-with-resources or explicit close calls as you did before. - Struts-specific tip: If you’re using Struts Actions, consider doing the JNDI lookup once in an action’s
init()method instead of every request to save overhead.
Yes, you absolutely need to configure Tomcat to define the JNDI connection pool. I recommend the project-specific approach for portability:
Project-Specific Configuration
Create or edit META-INF/context.xml in your web project. Add a <Resource> element to define your pool:
<Context> <Resource name="jdbc/YourDBPool" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/your_db" username="db_user" password="db_pass" maxTotal="100" <!-- Max total connections in the pool --> maxIdle="30" <!-- Max idle connections kept open --> maxWaitMillis="10000" <!-- Max time to wait for a connection (ms) --> removeAbandonedOnBorrow="true" <!-- Clean up stalled connections --> /> </Context>
Then, add a resource reference to your WEB-INF/web.xml so your app can access the pool:
<web-app> <!-- ... other existing config ... --> <resource-ref> <description>Database Connection Pool</description> <res-ref-name>jdbc/YourDBPool</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> </web-app>
Make sure the res-ref-name matches the name attribute in your context.xml resource.
Global Tomcat Configuration (Optional)
If you want this pool available to all apps on your Tomcat instance, edit $CATALINA_HOME/conf/server.xml and add the <Resource> inside the <GlobalNamingResources> section. Then link it to your app via context.xml, but this is less flexible for deployment.
You only need one key JAR, and the placement matters:
- Database Driver JAR: Put your DB driver (e.g.,
mysql-connector-java-5.1.49.jarfor MySQL) in$CATALINA_HOME/lib. This lets Tomcat load the driver class for the connection pool. If you put it in your app’sWEB-INF/lib, it might work, but placing it globally avoids duplication and ensures Tomcat can access it properly. - No extra JNDI/Struts JARs: Tomcat 7 already includes all the necessary JNDI and
javax.sqlclasses, and your existing Struts JARs should work fine with this setup.
- Restart Tomcat to apply the config changes.
- Test your app thoroughly to ensure connections are being fetched from the pool (check Tomcat’s logs for connection pool startup messages).
- Adjust the pool parameters (like
maxTotal) based on your app’s concurrent user load—start with conservative values and tweak as needed.
内容的提问来源于stack exchange,提问作者Aishwara S

