The Remarkable Everyday

Simple JNDI Accessing MySQL Datasource

Posted by leejeok on May 27, 2008

Base on the previous post, I have used the struts-config.xml to define the datasource to access to the MySQL database. The datasource class is code within the Action class (controller layer) and map to the struts-config.xml.


In order to improve the programming pratice, the datasource can be created via JNDI and the java code should be sit within the model layer. As a result, business logic will separate from the controller layer and making the Action class without knowing any relation with business class at all.


I am using Apache Tomcat 5.x and so, I will define the datasource resource via JNDI within the context.xml.


<Context path=”/bookstore”>

<ResourceLink global=”jdbc/bookstoreDB” name=”jdbc/bookstoreDB” type=”javax.sql.DataSource”/>



The java code to make the database connection accessing the JNDI would be look like this:


    Connection cn(){

        DataSource ds = null;


        try {

            Context ctx = new InitialContext();

            if ( ctx == null ) {

                throw new RuntimeException(“JNDI Context could not be found.”);


            ds = (DataSource)ctx.lookup(“java:comp/env/jdbc/bookstorDB”);


            if ( ds == null ) {

                throw new RuntimeException(“DataSource could not be found.”);


            return ds.getConnection();

            // Handle any JNDI errors

        } catch (NamingException ne) {

            throw new RuntimeException(“A JNDI error occured. ” + ne.getMessage());


        }catch(Exception e){

            System.err.println(“Boom – No Context”);


        return null;



Alternative, you can use JSP Standard Tag Library (JSTL) without embedding any Java code. I am using JSTL SQL tag here and may look like this:


<%@ taglib prefix=”sql” uri=”http://java.sun.com/jsp/jstl/sql&#8221; %>

<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core&#8221; %>


<sql:setDataSource dataSource=”jdbc/bookstoreDB” />


<sql:query var=”qryBooks” >

    SELECT bookID, bookTitle, bookAuthor, bookPublisher FROM book




    <c:forEach var=”row” items=”${qryBooks.rows}”>










One Response to “Simple JNDI Accessing MySQL Datasource”

  1. wilson said

    if there will be a problem, like you can’t run it. You may try to add the libraries:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: