Skip to content

Instantly share code, notes, and snippets.

@liweinan
Created September 13, 2012 12:25
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save liweinan/3713978 to your computer and use it in GitHub Desktop.
Save liweinan/3713978 to your computer and use it in GitHub Desktop.
Using JNDI in Tomcat7

Using JNDI in Tomcat7

Download HSQLDB from its website: [http://hsqldb.org]

Put hsqldb jars into Tomcat library:

cp hsqldb/lib/hsqldb.jar tomcat7/lib/

Edit tomcat7/conf/context.xml

    <Resource name="jdbc/MyDB" auth="Container"
        type="javax.sql.DataSource"
        maxActive="20"
        maxIdle="30"
        maxWait="10000"
        username="SA"
        driverClassName="org.hsqldb.jdbc.JDBCDriver"
        url="jdbc:hsqldb:file:///opt/hsqldb/db/mydb"/>

Create a table and put some data:

create table blogs (title varchar(255), body varchar(65535));
insert into blogs (title, body) values ('Article1','Body of Article1');
insert into blogs (title, body) values ('Article2','Body of Article2');

Put following config in web.xml

<resource-ref>
    <res-ref-name>jdbc/MyDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

Create a JSP page:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<h2>Blogs</h2>
<sql:query var="blogs" dataSource="jdbc/MyDB">select * from blogs;</sql:query>
<table border=1>
    <c:forEach var="blog" items="${blogs.rows}">
        <tr>
            <td><c:out value="${blog.title}"/>
            </td>
            <td><c:out value="${blog.body}"/>
            </td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

The output is as follow:

Blogs

Article1	Body of Article1
Article2	Body of Article2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment