Showing posts with label Servlets. Show all posts
Showing posts with label Servlets. Show all posts

Friday, 1 May 2015

JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle

🚀 Master Java & Backend Development!

Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and architecture guides!

👉 Click Here to Subscribe Now

What is C3P0 Connection Pooling?

In high-traffic Java web applications, opening and closing physical database connections repeatedly creates massive performance overhead. C3P0 is an open-source JDBC connection pool library that pre-initializes a pool of reusable connections. When your servlet requires database access, it simply borrows a connection from the pool and returns it when finished, significantly improving response times.

Step 1: Add Required JAR Files to Tomcat

To enable Tomcat and your application to use C3P0 with Oracle Database, copy the following JAR files directly into your Tomcat server's lib folder:

  • C3P0 JARs: Download the C3P0 library and place c3p0.jar and mchange-commons-java.jar into Tomcat/lib.
  • Oracle JDBC Driver: Add ojdbc6.jar (or compatible driver) into Tomcat/lib so Tomcat can communicate with Oracle.

Step 2: Configure the C3P0 DataSource in context.xml

Define the connection pool resource inside Apache Tomcat's context.xml file so it registers with the JNDI naming service:

<Resource name="jdbc/hrDB"
  auth="Container"
  type="com.mchange.v2.c3p0.ComboPooledDataSource"
  factory="org.apache.naming.factory.BeanFactory"
  driverClass="oracle.jdbc.OracleDriver"
  jdbcUrl="jdbc:oracle:thin:@localhost:1521:XE"
  user="hr"
  password="hr"
  maxPoolSize="50"
  minPoolSize="10"
  acquireIncrement="10" />

Step 3: Reference the Resource in web.xml

Declare the resource reference inside your web application's web.xml deployment descriptor:

<resource-ref>
  <description>Oracle DB Connection</description>
  <res-ref-name>jdbc/hrDB</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

Step 4: Retrieve and Use Connections in the Servlet

Inside your Servlet's init() method, perform a JNDI lookup to obtain the DataSource. Then, inside doGet(), retrieve a connection from the pool, execute SQL queries, and return output to the client:

Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/hrDB");

try (Connection conn = ds.getConnection();
     Statement stmt = conn.createStatement();
     ResultSet rs = stmt.executeQuery("SELECT employee_id, first_name, last_name, email FROM employees")) {
  while (rs.next()) {
    out.println(rs.getInt("employee_id") + " - " + rs.getString("first_name"));
  }
}

📺 Related Database & Connection Pooling Tutorials

Continue enhancing your Java backend knowledge with these related tutorials from our channel:


Click here to watch in Youtube : https://www.youtube.com/watch?v=Jkkd9qSuock&list=UUhwKlOVR041tngjerWxVccw&index=1

Click the below Image to Enlarge
JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle

EmployeeInfoServlet.java
import java.io.IOException;
import java.io.PrintWriter;
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.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

public class EmployeeInfoServlet extends HttpServlet
{

    private static final long serialVersionUID = 1L;

    DataSource                dataSource       = null;

    public void init( ServletConfig config )
    {
        try
        {

            System.out
                    .println("-----------------------------------------------------");
            System.out
                    .println("init method has been called and servlet is initialized");

            /*
             * Using JDNI lookup get the DataSource.
             */

            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            dataSource = (DataSource) envContext.lookup("jdbc/HRDB");

            System.out.println("Using JDNI lookup got the DataSource : "
                    + dataSource);

            System.out
                    .println("-----------------------------------------------------");
        }

        catch( Exception exe )
        {
            exe.printStackTrace();
        }

    }

    public void doGet( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException
    {

        System.out
                .println("-----------------------------------------------------");
        System.out.println("doGet method has been called");
        System.out
                .println("-----------------------------------------------------");

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        String title = "Employee Information From Oracle Database";
        out.print("<html><body bgcolor=\"#f0f0f0\">");
        out.print("<h1 align=\"center\">" + title + "</h1>\n");

        showEmployeeInformation(out);

        out.print("</body></html>");
    }

    public void destroy()
    {
        System.out
                .println("-----------------------------------------------------");
        System.out
                .println("destroy method has been called and servlet is destroyed");
        System.out
                .println("-----------------------------------------------------");
    }

    private void showEmployeeInformation( PrintWriter out )
    {
        Connection connection = null;
        Statement stmt = null;
        try
        {

            /*
             * Get connection from the DataSource
             */

            connection = dataSource.getConnection();

            /*
             * Execute the Query
             */

            stmt = connection.createStatement();
            String sql = "select employee_id,first_name,last_name,email,phone_number from employees";
            ResultSet rs = stmt.executeQuery(sql);

            /*
             * Iterate the ResultSet and get each row Information.
             */
            while( rs.next() )
            {
                /*
                 * Retrieve by column name
                 */
                int id = rs.getInt("employee_id");
                String firstName = rs.getString("first_name");
                String lastName = rs.getString("last_name");
                String email = rs.getString("email");
                String phoneNumber = rs.getString("phone_number");

                /*
                 * Display values
                 */
                out.print("employee_id: " + id+"<br>");
                out.print("first_name: " + firstName+"<br>");
                out.print("last_name: " + lastName+"<br>");
                out.print("email: " + email+"<br>");
                out.println("phone_number: " + phoneNumber+"<br>");
                out.println("-------------------------------------------");
            }
            rs.close();

        }

        catch( Exception e )
        {
            e.printStackTrace();
        }
        finally
        {
            /*
             * finally block used to close resources
             */
            try
            {
                if( stmt != null )
                {
                    stmt.close();
                }
            }
            catch( SQLException sqlException )
            {
                sqlException.printStackTrace();
            }
            try
            {
                if( connection != null )
                {
                    connection.close();
                }
            }
            catch( SQLException sqlException )
            {
                sqlException.printStackTrace();
            }
        }

    }

}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    metadata-complete="true" version="3.0">
    <display-name>EmployeeInfoDemo</display-name>
    <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>
    <servlet>
        <servlet-name>employeeInfoServlet</servlet-name>
        <servlet-class>EmployeeInfoServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>employeeInfoServlet</servlet-name>
        <url-pattern>/employeeInfo</url-pattern>
    </servlet-mapping>

    <resource-ref>
        <description>DB Connection</description>
        <res-ref-name>jdbc/HRDB</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

</web-app>
index.html
<!DOCTYPE HTML><html lang="en"><head>
<meta charset="UTF-8">
<title>Employee Information</title>
</head>
<body>
<p>
<h3>Employee Information</H3>
<p></p>
<ul>

<li><a href="employeeInfo">Show Employee Information</a></li>

</ul>
</body></html>

To Download EmployeeInfoDemoTomcatC3POOracleApp Project Click the below link

https://drive.google.com/file/d/1bnBxzVhyizv_f03BgFrSrSZPhbArVtFB/view

External Links:

Download the latest c3p0-{version}.jar from :  http://sourceforge.net/projects/c3p0/

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • Thursday, 30 April 2015

    JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql

    🚀 Master Java, JDBC & Web Technologies!

    Subscribe to Ram N Java for in-depth, beginner-friendly coding tutorials and architecture guides!

    👉 Click Here to Subscribe Now

    Why Use C3P0 Connection Pooling with MySQL?

    Creating database connections on every user request leads to high latency and heavy memory usage. C3P0 solves this problem by maintaining a pool of pre-established database connections. Instead of opening a brand-new connection each time, your Java Servlet borrows an existing connection from the pool, runs the SQL queries, and releases it back to the pool immediately.

    Step 1: Add Required Libraries to Tomcat

    Make sure the following JAR files are placed inside the Apache Tomcat/lib folder:

    • c3p0.jar & mchange-commons-java.jar: The core C3P0 connection pooling binaries.
    • mysql-connector-java.jar: The MySQL JDBC driver to allow Tomcat to communicate with your MySQL server.

    Step 2: Configure C3P0 DataSource in context.xml

    Define the MySQL connection pool resource inside your Tomcat configuration (META-INF/context.xml or conf/context.xml):

    <Resource name="jdbc/mysqldb"
      auth="Container"
      type="com.mchange.v2.c3p0.ComboPooledDataSource"
      factory="org.apache.naming.factory.BeanFactory"
      driverClass="com.mysql.jdbc.Driver"
      jdbcUrl="jdbc:mysql://localhost:3306/testdb"
      user="root"
      password="root"
      maxPoolSize="50"
      minPoolSize="10"
      acquireIncrement="5" />

    Step 3: Declare the Resource Reference in web.xml

    Inform your web application about the external DataSource resource in your web.xml deployment descriptor:

    <resource-ref>
      <description>MySQL Connection Pool</description>
      <res-ref-name>jdbc/mysqldb</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
    </resource-ref>

    Step 4: Perform JNDI Lookup and Query Data in Servlet

    Inside your servlet, look up the DataSource using JNDI and fetch records from MySQL:

    Context initContext = new InitialContext();
    Context envContext = (Context) initContext.lookup("java:comp/env");
    DataSource ds = (DataSource) envContext.lookup("jdbc/mysqldb");

    try (Connection conn = ds.getConnection();
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT id, username, email FROM users")) {
      while (rs.next()) {
        out.println(rs.getInt("id") + " : " + rs.getString("username"));
      }
    }

    📺 Related MySQL & Connection Pooling Tutorials

    Check out these related practical guides from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=5gSn9zt5qrA&list=UUhwKlOVR041tngjerWxVccw&index=2

    Click the below Image to Enlarge
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
    CityInfoServlet.java
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.sql.DataSource;
    
    public class CityInfoServlet extends HttpServlet
    {
    
        private static final long serialVersionUID = 1L;
    
        DataSource dataSource = null;
        
        public void init( ServletConfig config )
        {
            try
            {
    
                System.out
                        .println("-----------------------------------------------------");
                System.out
                        .println("init method has been called and servlet is initialized");
    
                /*
                 *  Using JDNI lookup get the DataSource.
                 */
                
                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup("java:/comp/env");
                dataSource = (DataSource) envContext.lookup("jdbc/worldDB");
                
                System.out.println("Using JDNI lookup got the DataSource : "+ dataSource);
    
                System.out
                        .println("-----------------------------------------------------");
            }
    
            catch( Exception exe )
            {
                exe.printStackTrace();
            }
    
        }
    
        public void doGet( HttpServletRequest request, HttpServletResponse response )
                throws ServletException, IOException
        {
    
            System.out
                    .println("-----------------------------------------------------");
            System.out.println("doGet method has been called");
            System.out
                    .println("-----------------------------------------------------");
    
            response.setContentType("text/html");
    
            PrintWriter out = response.getWriter();
            String title = "City Information From Mysql Database";
            out.print("<html><body bgcolor=\"#f0f0f0\">");
            out.print("<h1 align=\"center\">" + title + "</h1>\n");
            
            showCityInformation(out);
            
            out.print("</body></html>");
        }
    
        public void destroy()
        {
            System.out
                    .println("-----------------------------------------------------");
            System.out
                    .println("destroy method has been called and servlet is destroyed");
            System.out
                    .println("-----------------------------------------------------");
        }
    
        private void showCityInformation( PrintWriter out )
        {
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            try
            {
    
                String sql = "select * from city limit ?";
    
                /*
                 *  Get connection from the DataSource
                 */
                
                connection = dataSource.getConnection();
                
                /*
                 * Execute the query
                 */
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setInt(1, 10);
    
                ResultSet rs = preparedStatement.executeQuery();
    
                while( rs.next() )
                {
                    int id = rs.getInt(1);
                    String name = rs.getString(2);
                    String countryCode = rs.getString(3);
                    String district = rs.getString(4);
                    int population = rs.getInt(5);
    
                    /*
                     * Display values
                     */
                    out.print("ID: " + id + "<br>");
                    out.print("Name: " + name+ "<br>");
                    out.print("CountryCode: " + countryCode+ "<br>");
                    out.print("District: " + district+ "<br>");
                    out.println("Population: " + population+ "<br>");
                    out.println("--------------------------------------"+ "<br>");
                }
    
                rs.close();
    
            }
    
            catch( Exception e )
            {
                e.printStackTrace();
            }
            finally
            {
                /*
                 * finally block used to close resources
                 */
                try
                {
                    if( preparedStatement != null )
                    {
                        preparedStatement.close();
                    }
                }
                catch( SQLException sqlException )
                {
                    sqlException.printStackTrace();
                }
                try
                {
                    if( connection != null )
                    {
                        connection.close();
                    }
                }
                catch( SQLException sqlException )
                {
                    sqlException.printStackTrace();
                }
            }
    
        }
    
    }
    
    web.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        metadata-complete="true" version="3.0">
    
        <display-name>City Info Demo</display-name>
        <description>
            This is a simple web application with a source code organization
            based on the recommendations of the Application Developer's Guide.
        </description>
    
        <servlet>
            <servlet-name>cityInfoServlet</servlet-name>
            <servlet-class>CityInfoServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>cityInfoServlet</servlet-name>
            <url-pattern>/cityInfo</url-pattern>
        </servlet-mapping>
    
        <resource-ref>
            <description>DB Connection</description>
            <res-ref-name>jdbc/worldDB</res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
        </resource-ref>
    
    </web-app>
    
    index.html
    <!DOCTYPE HTML><html lang="en"><head>
    <meta charset="UTF-8">
    <title>City Information</title>
    </head>
    <body>
    <p>
    <h3>Show City Information</H3>
    <p></p>
    <ul>
    
    <li><a href="cityInfo">Show City Information</a></li>
    
    </ul>
    </body></html>
    
    
    To Download CityInfoDemoTomcatC3POMysqlApp Project Click the below link

    https://drive.google.com/file/d/1-oMKh79zw9FBJPsxa34GgX50raN1k12Z/view?usp=drive_web

    External Links:

    Download the latest c3p0-{version}.jar from :  http://sourceforge.net/projects/c3p0/

    See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JDBC|Servlets : Tomcat Connection Pooling - DBCP - Mysql

    🚀 Master Java, JDBC & Web Technologies!

    Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and architecture guides!

    👉 Click Here to Subscribe Now

    What is Apache Commons DBCP in Tomcat?

    Apache Commons DBCP (Database Connection Pooling) is the default connection pooling implementation packaged with Apache Tomcat. Instead of creating and tearing down database connections on every client request, DBCP manages a pool of active connections. Servlets can quickly borrow, utilize, and return connections to the pool, drastically improving web application performance and throughput.

    Step 1: Add the MySQL JDBC Driver to Tomcat

    Because Tomcat bundles DBCP natively inside tomcat-dbcp.jar, you only need to ensure the MySQL Connector driver JAR is present in your server's classpath:

    • Copy mysql-connector-java.jar into the Tomcat/lib directory.
    • Restart your Tomcat server so it can load the MySQL driver class.

    Step 2: Configure DBCP DataSource in context.xml

    Define the DBCP DataSource resource in your web application's META-INF/context.xml file:

    <Resource name="jdbc/mysqldb"
      auth="Container"
      type="javax.sql.DataSource"
      factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
      driverClassName="com.mysql.jdbc.Driver"
      url="jdbc:mysql://localhost:3306/testdb"
      username="root"
      password="root"
      maxTotal="20"
      maxIdle="10"
      minIdle="5"
      maxWaitMillis="10000" />

    Step 3: Declare the Resource Reference in web.xml

    Add the resource reference inside your web.xml deployment descriptor to map the JNDI lookup name:

    <resource-ref>
      <description>MySQL DBCP Connection Pool</description>
      <res-ref-name>jdbc/mysqldb</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
    </resource-ref>

    Step 4: Retrieve Connection and Execute Query in Servlet

    In your Java Servlet, look up the DataSource via JNDI and execute queries with automatic resource cleanup:

    Context initContext = new InitialContext();
    Context envContext = (Context) initContext.lookup("java:comp/env");
    DataSource ds = (DataSource) envContext.lookup("jdbc/mysqldb");

    try (Connection conn = ds.getConnection();
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT user_id, username, email FROM users")) {
      while (rs.next()) {
        out.println(rs.getInt("user_id") + " : " + rs.getString("username"));
      }
    }

    📺 Related Connection Pooling Tutorials

    Learn more about database architectures and connection pools from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=sXtfWahVEvk&list=UUhwKlOVR041tngjerWxVccw&index=3

    Click the below Image to Enlarge
    JDBC|Servlets : Tomcat Connection Pooling - DBCP - Mysql
    JDBC|Servlets : Tomcat Connection Pooling - DBCP - Mysql
    JDBC|Servlets : Tomcat Connection Pooling - DBCP - Mysql
    JDBC|Servlets : Tomcat Connection Pooling - DBCP - Mysql
    JDBC|Servlets : Tomcat Connection Pooling - DBCP - Mysql
    JDBC|Servlets : Tomcat Connection Pooling - DBCP - Mysql
    JDBC|Servlets : Tomcat Connection Pooling - DBCP - Mysql
    JDBC|Servlets : Tomcat Connection Pooling - DBCP - Mysql
    JDBC|Servlets : Tomcat Connection Pooling - DBCP - Mysql
    JDBC|Servlets : Tomcat Connection Pooling - DBCP - Mysql
    CityInfoServlet.java
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.sql.DataSource;
    
    public class CityInfoServlet extends HttpServlet
    {
    
        private static final long serialVersionUID = 1L;
    
        DataSource dataSource = null;
        
        public void init( ServletConfig config )
        {
            try
            {
    
                System.out
                        .println("-----------------------------------------------------");
                System.out
                        .println("init method has been called and servlet is initialized");
    
                /*
                 *  Using JDNI lookup get the DataSource.
                 */
                
                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup("java:/comp/env");
                dataSource = (DataSource) envContext.lookup("jdbc/worldDB");
                
                System.out.println("Using JDNI lookup got the DataSource : "+ dataSource);
    
                System.out
                        .println("-----------------------------------------------------");
            }
    
            catch( Exception exe )
            {
                exe.printStackTrace();
            }
    
        }
    
        public void doGet( HttpServletRequest request, HttpServletResponse response )
                throws ServletException, IOException
        {
    
            System.out
                    .println("-----------------------------------------------------");
            System.out.println("doGet method has been called");
            System.out
                    .println("-----------------------------------------------------");
    
            response.setContentType("text/html");
    
            PrintWriter out = response.getWriter();
            String title = "City Information From Mysql Database";
            out.print("<html><body bgcolor=\"#f0f0f0\">");
            out.print("<h1 align=\"center\">" + title + "</h1>\n");
            
            showCityInformation(out);
            
            out.print("</body></html>");
        }
    
        public void destroy()
        {
            System.out
                    .println("-----------------------------------------------------");
            System.out
                    .println("destroy method has been called and servlet is destroyed");
            System.out
                    .println("-----------------------------------------------------");
        }
    
        private void showCityInformation( PrintWriter out )
        {
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            try
            {
    
                String sql = "select * from city limit ?";
    
                /*
                 *  Get connection from the DataSource
                 */
                
                connection = dataSource.getConnection();
                
                /*
                 * Execute the query
                 */
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setInt(1, 10);
    
                ResultSet rs = preparedStatement.executeQuery();
    
                while( rs.next() )
                {
                    int id = rs.getInt(1);
                    String name = rs.getString(2);
                    String countryCode = rs.getString(3);
                    String district = rs.getString(4);
                    int population = rs.getInt(5);
    
                    /*
                     * Display values
                     */
                    out.print("ID: " + id + "<br>");
                    out.print("Name: " + name+ "<br>");
                    out.print("CountryCode: " + countryCode+ "<br>");
                    out.print("District: " + district+ "<br>");
                    out.println("Population: " + population+ "<br>");
                    out.println("--------------------------------------"+ "<br>");
                }
    
                rs.close();
    
            }
    
            catch( Exception e )
            {
                e.printStackTrace();
            }
            finally
            {
                /*
                 * finally block used to close resources
                 */
                try
                {
                    if( preparedStatement != null )
                    {
                        preparedStatement.close();
                    }
                }
                catch( SQLException sqlException )
                {
                    sqlException.printStackTrace();
                }
                try
                {
                    if( connection != null )
                    {
                        connection.close();
                    }
                }
                catch( SQLException sqlException )
                {
                    sqlException.printStackTrace();
                }
            }
    
        }
    
    }
    
    web.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        metadata-complete="true" version="3.0">
    
        <display-name>City Info Demo</display-name>
        <description>
            This is a simple web application with a source code organization
            based on the recommendations of the Application Developer's Guide.
        </description>
    
        <servlet>
            <servlet-name>cityInfoServlet</servlet-name>
            <servlet-class>CityInfoServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>cityInfoServlet</servlet-name>
            <url-pattern>/cityInfo</url-pattern>
        </servlet-mapping>
    
        <resource-ref>
            <description>DB Connection</description>
            <res-ref-name>jdbc/worldDB</res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
        </resource-ref>
    
    </web-app>
    
    index.html
    <!DOCTYPE HTML><html lang="en"><head>
    <meta charset="UTF-8">
    <title>City Information</title>
    </head>
    <body>
    <p>
    <h3>Show City Information</H3>
    <p></p>
    <ul>
    
    <li><a href="cityInfo">Show City Information</a></li>
    
    </ul>
    </body></html>
    
    
    To Download CityInfoDemoTomcatDBCPMysqlApp Project Click the below link

    https://sites.google.com/site/javaee4321/jdbc/CityInfoDemoTomcatDBCPMysqlApp.zip?attredirects=0&d=1

    External Links:

    http://commons.apache.org/proper/commons-dbcp/configuration.html

    http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html

    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • Older Posts Home

    Tutorials