Creating the Servlet (FirstServlet)

Now, its time to create the LifeCycleServlet which implements init(), service() and destroy() methods to demonstrate the lifecycle of a Servlet.

Java




// importing the javax.servlet package
// importing java.io package for PrintWriter
import javax.servlet.*;
import java.io.*;
 
// now creating a servlet by implementing Servlet interface
public class LifeCycleServlet implements Servlet {
 
    ServletConfig config = null;
 
    // init method
    public void init(ServletConfig sc)
    {
        config = sc;
        System.out.println("in init");
    }
 
    // service method
    public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException
    {
        res.setContenttype("text/html");
        PrintWriter pw = res.getWriter();
        pw.println("<h2>hello from life cycle servlet</h2>");
        System.out.println("in service");
    }
 
    // destroy method
    public void destroy()
    {
        System.out.println("in destroy");
    }
    public String getServletInfo()
    {
        return "LifeCycleServlet";
    }
    public ServletConfig getServletConfig()
    {
        return config; // getServletConfig
    }
}


Starting with first Servlet Application

To get started with Servlets, let’s first start with a simple Servlet application i.e LifeCycle application, that will demonstrate the implementation of the init(), service() and destroy() methods.
First of all it is important to understand that if we are developing any Servlet application, it will handle some client’s request so, whenever we talk about Servlets we need to develop a index.html page (can be any other name also) which will request a particular Servlet to handle the request made by the client (in this case index.html page).
To be simple, lets first describe the steps to develop the LifeCycle application : 

  • Creating the index.html page
  • Creating the LifeCycle Servlet
  • Creating deployment descriptor
     

Similar Reads

Creating the index.html page

For the sake of simplicity, this page will just have a button invoke life cycle. When you will click this button it will call LifeCycleServlet (which is mapped according to the entry in web.xml file)....

Creating the Servlet (FirstServlet)

...

Creating deployment descriptor(web.xml)

Now, its time to create the LifeCycleServlet which implements init(), service() and destroy() methods to demonstrate the lifecycle of a Servlet....

How to run the above program ?

...