Servlet Interface

As of now, we have created our servlet, we are done with the “HelloWorld” program in servlet. I hope you know how to create a servlet. In this article, we will discuss Interface in Servlet. As we know Interface in java is an abstract type that is used to specify behavior that the class must implement. So In Servlet Interface provides some methods that need to be implemented by the servlet.

What is Servlet Interface?

Servlet Interface provides some common methods that need to be implemented by the servlet. Servlet implements Servlet Interface directly or indirectly.

  • indirectly implementation is extending those class that implements servlet Interface. These classes are –Generic Servlet & HttpServlet.(Generic Servlet & HttpServlet will see it ahead).
  • directly by implementing Servlet Interface.

The Servlet Interface defines methods to initialize, to receive, and respond to requests and to destroy the resources. As we have seen theses are life-cycle methods. In addition to it, ServletInterface provides some methods for the servlet to use to get the information, and basic information about the servlet like its author, version, and copyright.

Methods of Servlet Interface

  • public void init(ServletConfig config): This method is for the initialization of servlet which is invoked only once by the servlet container. It is the life-cycle method of the servlet as we have seen earlier. It will be finished until the service request is accepted.
    • Parameters:
      • config: It contains servlet startup- information and initialization parameters.
  • public void service(ServletRequest req, ServletResponse res): This method handles the incoming request. This is invoked at every request for the client.
    • Parameters:
      • req: Client request of the servlet.
      • res: Servlet response to the client.
    • The request object req contains information about the service request.
    • The response object res contains information that is to be returned to the client.
  • public void destroy(): This method is invoked by the servlet container only once and is responsible for closing connection, removing thread, etc.
  • public ServletConfig  getServletConfig(): This method will return the object of Servletconfig.This method contains the initialization and startup information for the servlet. This returns the config object which contains startup information and initialization parameters of the servlet.
  • public String getServletInfo(): This method returns the information regarding servlets like author, version, and any copyright.

Let’s see the Example which implements servlet Interface.