Knowledge Walls
J2EE Technologies Tutorial
Hyderabad, Andhra Pradesh, India
How to use JNDI DataSource provided by Tomcat in Spring using jee:jndi-lookup Example
14325 Views
Hints 
Copy mysql-connector jar to tomcat lib directory.

Create db as "test" and create below books table.
CREATE DATABASE `test`;

CREATE TABLE books
(id int not null auto_increment primary key,
book_name varchar(200) not null);

INSERT INTO books(book_name) VALUES('Programming in C');
INSERT INTO books(book_name) VALUES('Java');
INSERT INTO books(book_name) VALUES('Spring');
INSERT INTO books(book_name) VALUES('Hibernate');
Step.1 Start a Web based Spring application 
  1. Select New menu -> Dynamic Web Project
  2. Enter Project Name as "SpringWithJNDIDataSourceExample"
  3. Click Next, Selecting Target runtime as Apache Tomcat 7.0
  4. Click Next, Check Generate web.xml deployment descriptor then click on "Finish"
  5. Copy and paste Spring's 21 Framework Jars and commons-logging-1.1.jar into /WEB-INF/lib
Tomcat server conf file server.xml
<GlobalNamingResources>
    <!-- Add below Resource tag; jdbc/test - test is the database name -->
    <Resource auth="Container"
              driverClassName="com.mysql.jdbc.Driver"
              global="jdbc/test"
              maxActive="100"
              maxIdle="20"
              maxWait="10000"
              minIdle="5"
              name="jdbc/test"
              password="mysql"
              type="javax.sql.DataSource"
              url="jdbc:mysql://localhost:3306/test"
              username="root" />
  </GlobalNamingResources>
Tomcat server conf file context.xml
<ResourceLink name="jdbc/test"
                    global="jdbc/test"
                    auth="Container"
                    type="javax.sql.DataSource" />
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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" id="WebApp_ID" version="3.0">
  <display-name>SpringWithJNDIDataSourceExample</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
  </welcome-file-list>
 
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/beans-servlet.xml </param-value>
  </context-param>
</web-app>
Beans-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
    
    <jee:jndi-lookup id="myDataSource"
                    jndi-name="jdbc/test"
                    expected-type="javax.sql.DataSource" />
    

</beans>
Project Explorer Preview 
ShowBookDetails.java
package com.springexample;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.support.WebApplicationContextUtils;

@WebServlet("/ShowBookDetails")
public class ShowBookDetails extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(req.getServletContext());
        DataSource dataSource = (DataSource) context.getBean("myDataSource");
        JdbcTemplate template = new JdbcTemplate(dataSource);
        List<Map<String,Object>> books = template.queryForList("SELECT * FROM books");
        
        for (Map<String,Object> book:books){
            resp.getWriter().write(book.get("id")+":"+book.get("book_name")+"<br />");
        }
    }
}
Output 
Run on Browser

Download as Zip 
Link to download
SpringWithJNDIDataSourceExample

Hints.
Click on File menu. then click "Download"
Best Lessons of "Spring 3.0 Examples"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details