Category Archives: tomcat

JAVA : Tomcat DataSources

How to create a MySQL DB Connection pool with Tom Cat

Inside META-INF folder create context.xml file and add following lines

<?xml version="1.0" encoding="UTF-8"?>
<Context>
	<!-- Test datasource -->
	<Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
		username="root" password="" driverClassName="com.mysql.jdbc.Driver"
		url="jdbc:mysql://localhost:3306/test" maxActive="2" maxIdle="1" />
</Context>

Inside WEB-INF folder open web.xml and add following lines (Child of web-app element)

<resource-ref>
    <description>Factory for java.sql.Connection</description>
    <res-ref-name>jdbc/test</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

Usage


private static final String INIT_CONTEXT_LOOKUP = "java:/comp/env";
private static final String ENV_CONTEXT_LOOKUP = "jdbc/test";

public static Connection getConnection() {
		Connection connection = null;
		try {
			Context initContext = new InitialContext();
			Context envContext = (Context) initContext
					.lookup(INIT_CONTEXT_LOOKUP);
			DataSource dataSource = (DataSource) envContext
					.lookup(ENV_CONTEXT_LOOKUP);
			return dataSource.getConnection();
		} catch (Exception ex) {
			log.error("connection", ex);
		}
		return connection;
	}