Servlet Interface and its Methods Explained with Example | Methods of Servlet Interface

Learn about Servlet Interface and its methods in detail by going through this tutorial. We will explain the purpose of all the methods with an example. Servlet Interface has five methods and is described below. Let us learn what is a Servlet Interface and the Methods supported by it.

What is the Servlet Interface?

All the servlets must implement the servlet interface. It defines the init(), service(), and destroy() methods that call by the server during the life cycle of a servlet. It also has a method that allows a servlet to obtain any initialization parameters.

Servlet Interface and its Methods

The methods define by servlet are given below:

1. public void init(ServletConfig sc) throws ServletException: It is called when the servlet initialized. The initialization parameter for the servlet can be obtained from sc. If you can’t initialize the servlet then you will get an Unavailable Exception.

2. public void service(ServletRequest req,ServletResponse res): It throws both ServletException, IOException
The Service() method is called to process a request from a client. You can read the request from a client from req. The response to the client can be written to res. You will get an Exception if IO and Servlet Problem Occurs.

3. public void destroy(): On completion of all pending requests or time out to the servlet, the server calls the destroy() method.

4. public String getServletInfo(): This method returns a string describing the servlet.

5. public ServletConfig getServletConfig(): This method returns a ServletConfig object that contains any initialization parameters.

Do Refer Similar Articles:

Java Servlet Interfaces with Examples

In this example, we have created a servlet by extending the Servlet Interface.

ServletInterfaceDemo.java file

Servlet interface and its methods explained with example 1

Web.xml file:

Servlet interface and its methods explained with example 2

Output:

Servlet interface and its methods explained with example 3