Over a million developers have joined DZone.

Connection Pooling in a Java Web Application with Tomcat and NetBeans IDE

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

After my article Connection Pooling in a Java Web Application with Glassfish and NetBeans IDE, here are the instructions for Tomcat.


  • NetBeans IDE (this tutorial uses NetBeans 7)
  • Tomcat (this tutorial uses Tomcat 7 that is bundled within NetBeans)
  • MySQL database
  • MySQL Java Driver


Assuming your MySQL database is ready, connect to it and create a database. Lets call it connpool:

mysql> create database connpool;
Now we create and populate the table from which we will fetch the data:

mysql> use connpool;
mysql> create table data(id int(5) not null unique auto_increment, name varchar(255) not null);
mysql> insert into data(name) values("Fred Flintstone"), ("Pink Panther"), ("Wayne Cramp"), ("Johnny Bravo"), ("Spongebob Squarepants");

That is it for the database part.

We now create our web application.

In NetBeans IDE, click File → New Project... Select Java Web → Web Application:

NetBeans New Web Application

Click Next and give the project the name TomPool. Click Next

New Web App

Choose the server as Tomcat and, since we are not going to use any frameworks, click Finish.

Choose Tomcat

The project will be created and the start page, index.jsp, opened for us in the IDE.

Now we create the connection pooling parameters. In the Projects window, expand configuration files and open "context.xml". You will see that the IDE has added this code for us:

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/TomPool"/>

Delete the last line:

<Context antiJARLocking="true" path="/TomPool"/>

and then add the following to the context.xml file. I have explained the sections along the way. Make sure you edit your MySQL username and password appropriately:

<Context  antiJARLocking="true" path="/tompool">
    <!-- maxActive: Maximum number of database connections in pool. Make sure you
         configure your mysqld max_connections large enough to handle
         all of your db connections. Set to -1 for no limit.

    <!-- maxIdle: Maximum number of idle database connections to retain in pool.
         Set to -1 for no limit.  See also the DBCP documentation on this
         and the minEvictableIdleTimeMillis configuration parameter.

    <!-- maxWait: Maximum time to wait for a database 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.

    <!-- username and password: MySQL username and password for database connections  -->

    <!-- driverClassName: Class name for the old mm.mysql JDBC driver is
         org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
         Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.

    <!-- url: The JDBC connection url for connecting to your MySQL database.

    <Resource name="connpool" auth="Container" type="javax.sql.DataSource"
            maxActive="100" maxIdle="30" maxWait="10000"
            username="arthur" password="password" driverClassName="com.mysql.jdbc.Driver"


Next, expand the Web Pages node, right-click WEB-INF → New → Other → XML → XML Document.

Click Next and type web for the File Name. Click next and choose Well-Formed Document then Finish. You will now have the file "web.xml":

New File

JSP Page

Delete everything in the file and paste this code:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    <description>MySQL Test App</description>
        <description>DB Connection</description>

That is it for the connection pool. We now edit our code to make use of it.

Edit index.jsp by adding this code just after the initial coments but before <%@page contentType=...

<%@page import="javax.naming.Context"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.Connection"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="javax.naming.InitialContext"%>

JSP Edit

Edit the <body> section of the page:

        <h1>Data in my Connection Pooled Database</h1>
            InitialContext initialContext = new InitialContext();
            Context context = (Context) initialContext.lookup("java:comp/env");
            //The JDBC Data source that we just created
            DataSource ds = (DataSource) context.lookup("connpool");
            Connection connection = ds.getConnection();

            if (connection == null)
                throw new SQLException("Error establishing connection!");
            String query = "SELECT name FROM variable";

            PreparedStatement statement = connection.prepareStatement(query);
            ResultSet rs = statement.executeQuery();

            while (rs.next())
                out.print(rs.getString("name") + "< br >");

Now, we test the connection pool by running the application:



If you want to have the one connection pool used in multiple applications, you need to edit the following two files:

1. <tomcat_install_folder>/conf/web.xml

Just before the closing </web-app> tag, add the code

        <description>DB Connection</description>

2. <tomcat_install_folder>/conf/context.xml

Just before the closing </Context> tag, add the code

<Resource name="connpool" auth="Container" type="javax.sql.DataSource"
              maxActive="100" maxIdle="30" maxWait="10000"
              username="arthur" password="password" driverClassName="com.mysql.jdbc.Driver"
Now you can use the pool without editing XML files in each of your applications. Just use the sample code as given in index.jsp



That's it folks!

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}