Servlet Life Cycle Example with JDBC

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

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

Servlet Program: LifeDemo.java

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().


ima
Output Screenshot on Servlet Life Cycle