Servlet Interface

Java provides a servlet interface in javax.servlet package that is implemented by servlet program either directly or indirectly. This interface provides five methods and these methods must be declared within the servlet program if we are implementing a servlet interface. So implementing the servlet interface is a direct approach.

We also discuss about the indirect approach later.

Methods of Servlet interface

Methods provided by servlet interface are mentioned below.

Method

Description

public void init(ServletConfig con)

This method is invoked by servlet container once only. The purpose of it is to indicate that the servlet is ready to use.

public void service(ServletRequest req,ServletResponse) throws ServletException

This method is invoked every time whenever a response is given to a request. So this method is used to perform actual tasks.

public ServletConfig getServletConfig()

This method return an object of ServletConfig that contains initialization parameters of the servlet.

public String getServletInfo()

This method is used to provide the information about the servlet.

public void destroy()

This method is invoked by servlet container once only. It is used to indicate that now the server is terminated and no more tasks will execute.

First servlet program using Servlet interface  This is the simple example of servlet interface with its methods. FirstServlet.java
import javax.servlet.*;
public class FirstServlet implements Servlet
{
      public void init(ServletConfig con)
            {          
                        System.out.println("init method is invoked once only");
            }
            public void service(ServletRequest req,ServletResponse res) throws ServletException
            {
                        System.out.println("service method is invoked");
            }
            public ServletConfig getServletConfig()
            {
                        return null;
            }
            public String getServletInfo()
            {
                        return "info";
            }
            public void destroy()
            {
                        System.out.println("destroy method is invoked once only");
            }
            }
Web.xml Now we have to deploy are servlet class in web.xml file. So, open your web.xml file and edit the required tag.
<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
<servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
</web-app>
Output: See here init() method and service() method is invoked but destroy() method is still not invoked. This is because server is still in running mode. Output: Everytime when we refresh our page service() method is invoked. As soon as we stop the server destroy() method is also invoked which indicates that now no more task will execute.