Wednesday, May 12, 2010

In this article I'll explain each step you need to know to display records from the database using Servlets. The steps for displaying records in JSP pages and Java Beans are almost the same. We will first build a small example Microsoft Access database, create a DSN for it and using JDBC ( Java Database Connectivity ) driver connect with it and display the records from a given table. Since 80% of your time developing applications will be spent on interacting with databases, you should pay utmost importance to this article.
Access DatabaseYou can use any database of your choice but for this article I will stick with Microsoft Access database on a Windows platform.
Create a new Access database with the name of 'odbc_exmp.mdb' and create a table 'Names' containing three fields 'ID', 'first_name' and 'last_name' where 'ID' is the primary key :
Names - Table
Go to the control panel and create a new DSN ( Data Source Name ) 'odbc_exmp' for it and point it to the path of your database on your computer.
Populate the 'Names' table with any values like the following so that we can display the records later :
Names - Table
DisplayServletCreate a new DisplayServlet.java file in the /APP_NAME/WEB-INF/classes/com/stardeveloper/servlets/db/ folder. Note /APP_NAME/ is the path of your application within your application server, in Tomcat 4.0 /APP_NAME/ will be /CATALINA_HOME/webapps/star/ where 'star' is the name of the application.
Copy and paste the following code into DisplayServlet.java file and compile it :package com.stardeveloper.servlets.db; import java.sql.*;import java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class DisplayServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.print(""); out.print(""); out.print("
"); out.print("? "); out.print("Display Records
"); out.print(""); out.close(); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.print(""); out.print(""); out.print("
");    out.print("ID\tFirst ");    out.println("Name\tLast Name\n");     // debugging info     long time1 = System.currentTimeMillis();     // connecting to database     Connection con = null;    Statement stmt = null;    ResultSet rs = null;     try {      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");      con = DriverManager.getConnection("jdbc:odbc:odbc_exmp");       stmt = con.createStatement();      rs = stmt.executeQuery("SELECT * FROM Names");       // displaying records       while(rs.next()) {        out.print(rs.getObject(1).toString());        out.print("\t");        out.print(rs.getObject(2).toString());        out.print("\t\t");        out.print(rs.getObject(3).toString());        out.print("\n");      }       } catch (SQLException e) {      throw new       ServletException("Servlet Could not display records.", e);    } catch (ClassNotFoundException e) {      throw new       ServletException("JDBC Driver not found.", e);    } finally {      try {        if(rs != null) {          rs.close();          rs = null;        }        if(stmt != null) {          stmt.close();          stmt = null;        }        if(con != null) {          con.close();          con = null;        }      } catch (SQLException e) {}    }     // debugging info     long time2 = System.currentTimeMillis();     out.print("
"); out.print("

Search took : "); out.print( (time2 - time1) ); out.print(" ms.

"); out.print("Back

"); out.print(""); out.close(); }}

Start your application server and point your browser to http://localhost:8080/star/servlet/com.stardeveloper.servlets.db.DisplayServlet to see the Servlet display records on your computer. To see the demo please move on to the last page of this article.
Steps of Connecting to DatabaseIn the previous page we developed a Servlet 'DisplayServlet' which extends HttpServlet class and overrides doGet() and doPost() methods. In the doGet() method we display a Form to the user to click, after which he will be shown records from our 'odbc_exmp.mdb' database. Nothing much to talk about yet. In doPost() method we make a connection to the database and iterate through it's records. This is the method which needs more explanation.