Wednesday, 21 November 2012

J2ee Tutorial Part 5 :- Exploring the Servlet Life Cycle

// Exploring the Servlet Life Cycle here we will closely observe the order of execution of lifecycle methods
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class LifeCycle extends HttpServlet {

    public static int instanceCount;
    {
        System.out.println("Doing static initialization on LifeCycle class");
        instanceCount = 0;

    }

    public void init() {
        System.out.println("In init() on LifeCycle");
    }

    public LifeCycle() {
        instanceCount++;
        System.out.println("In LifeCycle constructor");
    }

    public void destroy() {
        System.out.println("In destroy() on LifeCycle");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("In doGet() on LifeCycle");
        try {
            throw new Exception();
        } catch (Exception e) {
            // Just doing this to show doGet() called from service()
            e.printStackTrace();
        }
    }

}

Output :-//Bellow you can see the order in which lifecycle methods are called
Doing static initialization on LifeCycle class
In LifeCycle constructor
In init() on LifeCycle
In doGet() on LifeCycle
In destroy() on LifeCycle

No comments:

Post a Comment

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...