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