by Dinesh Thakur Category: Servlet with MySql Database

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

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();
            }
}




About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles