Servlet Life Cycle Example with JDBC

After learning what Servlet life cycle is and the methods involved, let us go for an example involving the life cycle methods. I take the opportunity to connect to database and read table records using life cycle methods. Or to say, illustration of life cycle methods and learning JDBC through Servlet goes in a single example.

No separate JDBC exist for Servlets. The same JDBC steps, you know earlier, are written in service() method. Because this is life cycle example, the connection to database is established in init() method, records are read in service() method and closed in destroy() method. Infact, everything can be written in service() method itself.

Example on Servlet Life Cycle using Methods

In the following program, at the request of the client, the Servlet retrieves the records from the database table Employee and send them to the client. The records are printed in a table.

Client HTML file requesting records: LifeDemo.html


Click for Employee Records

LD is the alias name of LifeDemo servlet declared in web.xml.

Servlet Program:

import javax.servlet.*;
import javax.servlet.http.*;         
import java.sql.*;

public class LifeDemo extends HttpServlet     
  Statement stmt;
  Connection con;
  ResultSet rs;
                                      // first life cycle method
  public void init(ServletConfig config) throws ServletException   
    super.init(config);               // this statement throws ServletException

    try                               // establish database connection in init()
      con=DriverManager.getConnection("jdbc:odbc:snrao", "scott", "tiger");
    catch(Exception e) { e.printStackTrace();  }
                                      // second life cycle method
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException   
    PrintWriter out=res.getWriter();
      rs=stmt.executeQuery("Select * from Employee");

Employees Particulars

"); out.println(""); out.println(""); while( // retrieve records { out.println(""); } out.println("
Emp ID Emp Name Emp Salary
" + rs.getInt(1) + "" + rs.getString(2) + "" + rs.getDouble(3) + "
"); } catch(Exception e) { e.printStackTrace(); } out.close(); } // third life cycle method public void destroy() { try // close the database connections { if(rs != null) rs.close(); if(stmt != null) stmt.close(); if(con != null) con.close(); } catch(SQLException e) { e.printStackTrace(); } } }

For JDBC code explanation, an exact similar program is available at Select Records Example without using Servlet.

The exception message can be printed in three ways and one is printStackTrace().

Output Screenshot on Servlet Life Cycle