Servlet Life Cycle Example

Servlet Life Cycle Example

Posted in : Servlet Posted on : November 1, 2010 at 5:31 PM Comments : [ 0 ]

In this tutorial you will learn about the servlet life example which shows how the methods of life cycle are called

Servlet Cycle Simple Example

Every servlet have their own life cycle in which they perform their task. Every servlet calls init(), service(), and destroy() method in their life cycle. If you do not write init() and destroy() the container call it implicitly. An example of servlet life cycle is given below.


import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletLifeCycleExample extends HttpServlet {
\// Servlet init() method
	public void init() {
		System.out.println("\n\n Servlet Init() Method");
		System.out.println("Servlet Initialised by init() method");

	public void init(ServletConfig config) {
		try {
			System.out.println("\n\nServlet init(config)method\n");
			System.out.println("Servlet Initialised by init(context) method");
		} catch (ServletException e) {
			// TODO Auto-generated catch block

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		out.println("Servlet Life Cycle Example");
		System.out.println("Inside doGet() method");


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);

	public void destroy() {
		System.out.println("\n\nServlet destroyed \n");
		System.out.println("Servlet Finalising by destroy() method");

When you run this application it will display message as shown below:

On Browser

On Tocat Console....

Download this example code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics