The following steps show the different methods used in Servlet Life Cycle.
Creating servlet instance: The web container creates an object for the servlet when servlet class is loaded, here the important point is an object will be created in life cycle only once.
init method: This method will be called by the web container after an object was created to the servlet. The functionality of the init() method is to initialize the servlet, following is the regular syntax to declare the init() method.
public void init(ServletConfig config) throws ServletException
service method: The service() method will be called by web container when servlet will have the request, in case servlet is not initialized then above methods will be utilized. In the life cycle of servlet this method will be utilized only once. Following is a syntax to declare the service() method.
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
destroy method: Web container is the responsibility to call this method utilized while vanishing an object of the Servlet from the service, it provides the chance for servlet to clean up the memory or junk data. Following is the Syntax for the destroy method.
public void destroy()
Following is the code structure of life cycle methods.
package servletinterface; import java.io.*; import javax.servlet.*; public class First implements Servlet{ ServletConfig config=null; public void init(ServletConfig config){ this.config=config; System.out.println("servlet is initialized"); } public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.print("<html><body>"); out.print("<b>Hey man, welcome to SPLesons.</b>"); out.print("</body></html>"); } public void destroy(){System.out.println("servlet is destroyed");} public ServletConfig getServletConfig(){return config;} public String getServletInfo(){return "copyright 2007-1010";} }
web.xml
Sample rule of WEB.XML file as follows.
<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>servletinterface.First</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
index.html
<center><a href="./hello">Invoke Generic Servlet</a></center>
Output
By compiling the program the follolwing output get generated.
By clicking on the link following output will be generated.