Signup · Login
Stardeveloper.com  
Home · Tutorials · Forums · ASP.NET Newsletter Application · Web Hosting Plans · Faisal Khan's Blog · Contact
Search Stardeveloper.com
Newsletter
Enter your email address to receive full length articles at Stardeveloper:


Article Categories
.NET  .NET
  ASP (16)
  ASP.NET (41)
  ADO (16)
  ADO.NET (11)
  COM (6)
  Web Services (4)
  C# (1)
  VB.NET (3)
  IIS (2)

J2EE  J2EE
  JSP (15)
  Servlets (9)
  Web Services (1)
  EJB (4)
  JDBC (4)
  E-Commerce (1)
  J2ME (1)
  Products (1)
  Applets (1)
  Patterns (1)
Log In
UserName Or Email:

Password:

Auto-Login:

Miscellaneous Links
  Submit Article
Stardeveloper RSS Feed
Hosted by Securewebs.com
 
Home : J2EE : Servlets : Displaying Records from the Database with Java Servlets
 
RSS - Read full length articles at Stardeveloper using Stardeveloper RSS Feed RSS

Displaying Records from the Database with Java Servlets

by Faisal Khan. Follow Faisal Khan on Twitter Follow Faisal Khan on Facebook

Overview
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 Database
You 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
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
Names - Table

DisplayServlet
Create 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("<html><head>");
    out.print("</head><body>");

    out.print("<form action=\"");
    out.print( req.getRequestURI() );
    out.print("\" method=\"post\">");
    out.print("<input type=\"submit\" ");
    out.print("value=\" \">  ");
    out.print("Display Records</form>");

    out.print("</body></html>");

    out.close();
  }

  public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.print("<html><head>");
    out.print("</head><body>");

    out.print("<code><pre>");
    out.print("<font color=green>ID\tFirst ");
    out.println("Name\tLast Name\n</font>");

    // 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("</pre></code>");

    out.print("<p>Search took : ");
    out.print( (time2 - time1) );
    out.print(" ms.</p>");

    out.print("<p\"><a href=\"");
    out.print( req.getRequestURI() );
    out.print("\">Back</a></p>");

    out.print("</body></html>");
    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 Database
In 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.


 ( 1 Remaining ) Next

Comments/Questions ( Threads: 14, Comments: 19 )
    Contains 1 or more replies by the Author of this Article.
    Contains 1 or more replies by Faisal Khan.

  1. First followed your instructions for installing Tomcat 6.0 - Where to place this file now?
  2. Displaying Records from the Database with Java Servlets
  3. getting hold of package and servlet
  4. not getting form
  5. Displaying records from MS Access using Java Servlets
  6. To upload jpeg files from one folder to another folder using JSP and servlets
  7. Displaying Records from the Database with Java Servlets
  8. how to connect my database from sqlsever2000 sgbd to my jsp page
  9. Great tutorial - I have question !! Please Help
  10. Using Java Servlets
  11. request for folder creation ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  12. how to complile this servlet ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  13. Servlet: Display records ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  14. Figures ( 2 Replies ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.

Post Comments/Questions

In order to post questions/comments, you must be logged-in. If you are not a member yet, then signup, otherwise login. Once you login then come back to this page and you'll see a form right here which will allow you to post comments/questions.

Please note, one of the benefits of signing up is to be notified immediately by email everytime you receive a reply to the thread you have subscribed.

 
© 1999 - 2010 Stardeveloper.com, All Rights Reserved.