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.



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.


Now we have to deploy are servlet class in web.xml file. So, open your web.xml file and edit the required tag.


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.


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.

Pin It on Pinterest

Share This