MySQL DataSource Configuration in Tomcat 7

If we are getting "javax.naming.NameNotFoundException: Name jdbc is not bound in this Context" exception it means MySql Datasource is not configured to the web-application context.

Let us see how to configure MySql Datasource in Tomcat 7.

  1. Download Latest jdbc connector and add to web-application libraries. MySql Connectors
  2. Add a 'META-INF/context.xml' to web-application root directory and define database connection detail as follows.

    <Context>
        <Resource
            name="jdbc/
    dfbdb" auth="Container"
            type="javax.sql.DataSource"
               maxActive="50" maxIdle="30" maxWait="10000"
             username="mysqluser" password="mysqlpassword"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/dfbdb"/>
    </Context>
  3.  Add datasource definition to web-application web.xml as follows

    <resource-ref>
        <description>MySQL Datasource</description>
        <res-ref-name>jdbc/dfbdb</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
      </resource-ref>
  4. Now we create javax.sql.DataSource object as follows.

    try {
                Context ctx = new InitialContext();
                ds = (DataSource)ctx.lookup("java:comp/env/jdbc/dfbdb");
    } catch (NamingException e) {
                e.printStackTrace();
    }

 Note: 'META-INF/context.xml' file is referenced only if there exist no context.xml file under $CATALINA/conf/your-host/your-app.xml

No comments:

Post a Comment