Java, Software Development, Tomcat

Connecting Tomcat 7 Web Application to Database Using JNDI

Several weeks ago, I looked at some decompiled Java codes from a fairly small web application that basically records cheque numbers and generates reports.  To my surprise, it was written in dreadful codes full of clutter and signs of haste! I almost cried. Just imagine the following code littered all around the application and entangled by a lot of package-level instance variables. Not to mention the SQL-statements-in-Servlets type of design pattern.

Thus, this blog.

This is how I do things.

Software Applications used

  1. Tomcat 7.0.23
  2. JDK1.6
  3. Eclipse
  4. HSQL 2.2.6

Step 1 – Download and set up HSQL Database

Please see Tomcat 7 and Up: JDBC Realm on how to create a database and start the HSQL server. For this blog, we will use

blog-20111201-002

Create table and insert sample data

blog-20111201-003

Test Data

Step 2– Create an Eclipse project and Servlet that uses our database.

The workspace.

blog-20111201-001

Java project in Eclipse

The Servlet code

WARNING: This is just for demonstration purposes. Do not put SQLs in your Servlets.

The web.xml

The web applicaiton directory structure and the required HSQL jar file.

blog-20111201-005

The Web App dir and required HSQL jar file

Step 3 – Configure Tomcat7

a) Add the following between the context tags in <TOMCAT_HOME>/conf/context.xml

Step 4 – Start Tomcat and Test the web application

blog-20111201-006

And you are done!

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like