Servlet Interface Tutorial

Servlet interface needs to be implemented for creating any servlet. There are 5 methods in Servlet interface . But The init, service and destroy are the life cycle methods of servlet. These are invoked by the web container.and 2 non-life cycle methods.

Method Description

  1. public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once.
  2. public void service(ServletRequest request,ServletResponse response) provides response for the incoming request. It is invoked at each request by the web container.
  3. public void destroy() is invoked only once and indicates that servlet is being destroyed.
  4. public ServletConfig getServletConfig() returns the object of ServletConfig.
  5. public String getServletInfo()returns information about servlet such as writer, copyright, version etc.

import javax.servlet.*;  
public class First implements Servlet{  
ServletConfig config=null;  
public void init(ServletConfig config){  
System.out.println("servlet is initialized");  
public void service(ServletRequest req,ServletResponse res)  
throws IOException,ServletException{  
PrintWriter out=res.getWriter();  
out.print("This is  simple First  servlet");  
out.print("	");  
public void destroy(){System.out.println("servlet is destroyed");}  
public ServletConfig getServletConfig(){return config;}  
public String getServletInfo(){return "copyright 2014-2015";}