• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Servlet » Database » Multi-tier Applications using JDBC from a Servlet
Next →
← Prev

Multi-tier Applications using JDBC from a Servlet

By Dinesh Thakur

Servlets are the server-side components that enhance the capability of Java-enabled servers and allow a variety of network-based services. For example, servlets with the database communication can facilitate solutions for distributed applications.

Typical three-tier architecture for database applications is shown in the Figure. The first tier (client) contains a browser (such as Netscape or Microsoft IE). The second tier contains the Java-enabled web server and the JDBC driver (for example, JDBC-ODBC bridge driver). The database is contained in the third tier. Servlets allow dynamic HTML pages to communicate with the client and database through JDBC.

                Three-tier architecture

We’ll be covering the following topics in this tutorial:

  • Writing JDBC/Servlet
  • A sample JDBC/Servlet application

Writing JDBC/Servlet

Consider the example of the TestDataBaseCon servlet in Program which illustrates the use of the servlet framework in JDBC/Servlet communication. This servlet makes a connection to the database and returns data in HTML form.

Program Making a database connection using the init() method.

public class TestDataBaseCon extends HttpServlet
{
       Connection connection = null;
       public void init() throws ServletException
      {
              try
              {
                      String host = config.getlnitParameter("host");
                      String uname = config.getlnitParameter("user");
                      String pwd = config.getlnitParameter("Password");
                      Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
                      url = "jdbc:microsoft:SqIServer://"+host+":1433;"+
                        "User = "+uname+ "Password="+pwd;
                      con= DriverManager.getConnection(url);
               }
                      catch(ClassNotFoundException e)
                           {
                                 System.out.println("problem in loading the class:");
                           }
                      catch(SQLException e)
                          {
                                   System.out.println("Sql error");
                           }
       }
}

Servlets are built by extending a basic Servlet class and overriding some of the methods to deal with incoming client requests. TestDataBaseCon extends the HttpServlet class that provides most of the capabilities needed to serve client requests. After the servlet is loaded, three main methods are involved in the life-cycle of a servlet.

Initialization

On receiving the request from the client, the servlet engine (container) checks whether it is the first request to the servlet. If it is the first request, then the servlet engine instantiates the servlet and initializes it by sending the initialization method call that is, init(). The code related to database connections is placed in the init() method.

Service calls

After initialization, servlets are capable of handling many requests, by means of a single servlet instance. Each client request generates one service call (that is, thread to provide service) and these calls can be concurrent. In a JDBC servlet, the service calls process incoming name value pair information from a browser, and return raw data or HTML pages (dynamic or static) as output. Note that in the name-value pair, the name indicates the parameter name and value indicates the value(s) of that parameter.

Servlet termination

The destroy method provided by the HttpServlet class destroys the servlet and logs the destruction. This method is overridden to destroy the resources used in the servlet. The destroy method should undo any initialization work that is done in the init() method. In the TestDataBaseCon example of Program, the destroy method is the used for this purpose.

Program Using the destroy method for servlet termination.
public class TestDataBaseCon extends
{
        Connection connection =  null;
          // init() method
         // service() method
       public void destroy()
       {
                   // Close the connection and allow it to be garbage collected
                   connection.close();
                connection =  null;
       }
}

A server calls the destroy method after all service calls have been completed, or a server specific number of seconds have passed without there being any request from the client. If the servlet handles any long-running operations, the service methods might still be running when the server calls the destroy method. Hence, it must be ensured that those threads complete their function. The destroy method described in Program expects all client interactions to be completed when it is called, because the servlet has no long-running operations.

A sample JDBC/Servlet application

Program gives a simple JDBC/Servlet application . 
Program Illustration of initializing, implementing and destroying a servlet.
public class TestDataBaseCon extends HttpServlet
{
  //declaration of the connection
  private Connection con;
  public void init(ServletConfig conf) throws ServletException
  {
           // initializing the servlet
          super.init( conf);
           try
          {
               String host = config.getlnitParameter("host");
               String dsource = config.getlnitParameter("dsource");
               String uname = config.getlnitParameter("uname");
               String pwd = config.getlnitParameter("pwd");
                // loading the driver class and registering to DriverManager
               Class.forName(" oracle.jdbc.driver.OracleDriver");
                 //getting connection
               ur1="jdbc:oracle:thin:@"+host+":1521:"+dsource;
               con =DriverManager.getConnection( url,uname,pwd);
          }
                catch (ClassNotFoundExcepticn e)
               {
                       System.out.pritnln ("Driver class is not found:" + e.getMessage());
                }
                catch (SQLException se)
                {
                       System.err.println("Problem in making the connection:" + se);
                 }
    }
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException
{
               res.setContent Type("text/html");
    try
  {
            PrintWriter pout = res.getWriter();
            pout.println("<html>");
            pout.println("<head>");
            pout.println("<title>Sample JDBC Servlet Demo</title>");
            pout.println ("<lhead>");
            pout.println("<body >");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("select * from Emp_info");
             pout.println("Getting the values from the Oracle Table")
             while(rs.next())
             {
                         pout.println(rs.getString(1)+" ");
                         pout.println (rs.getString(2));
               }
                          pout.println();
                          rs.c1ose();
                          stmt.c1ose();
   }
             catch(SQLException e)
          {
                        // SqlException describes problem with connection
                         pout.println("An SQL Exception was thrown.");
         }
             catch(IOException e)
            {
                        pout.println("An IOException was thrown.");
              }
             pout.println("</body>");
             pout.println ("</html>");
   }
             //closing the connection to the database
             public void destroy()
            {
                   con.c1ose();
            }
}

You’ll also like:

  1. MySql OrderBy Multi Columns in Java Servlet
  2. What are Multi Tasking, Multi Programming and Multi Threading
  3. What is JDBC API? Important Goals of JDBC-API.
  4. WHAT IS JDBC?
  5. Explain About JDBC Architecture
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

SQL Tutorials

SQL Tutorials

  • SQL - Home
  • SQL - Select
  • SQL - Create
  • SQL - View
  • SQL - Sub Queries
  • SQL - Update
  • SQL - Delete
  • SQL - Order By
  • SQL - Select Distinct
  • SQL - Group By
  • SQL - Where Clause
  • SQL - Select Into
  • SQL - Insert Into
  • SQL - Sequence
  • SQL - Constraints
  • SQL - Alter
  • SQL - Date
  • SQL - Foreign Key
  • SQL - Like Operator
  • SQL - CHECK Constraint
  • SQL - Exists Operator
  • SQL - Drop Table
  • SQL - Alias Syntax
  • SQL - Primary Key
  • SQL - Not Null
  • SQL - Union Operator
  • SQL - Unique Constraint
  • SQL - Between Operator
  • SQL - Having Clause
  • SQL - Isnull() Function
  • SQL - IN Operator
  • SQL - Default Constraint
  • SQL - Minus Operator
  • SQL - Intersect Operator
  • SQL - Triggers
  • SQL - Cursors

Advanced SQL

  • SQL - Joins
  • SQL - Index
  • SQL - Self Join
  • SQL - Outer Join
  • SQL - Join Types
  • SQL - Cross Join
  • SQL - Left Outer Join
  • SQL - Right Join
  • SQL - Drop Index
  • SQL - Inner Join
  • SQL - Datediff() Function
  • SQL - NVL Function
  • SQL - Decode Function
  • SQL - Datepart() Function
  • SQL - Count Function
  • SQL - Getdate() Function
  • SQL - Cast() Function
  • SQL - Round() Function

Other Links

  • SQL - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW