Servlet interface and its methods explained with example

In this tutorial, we will learn about Servlet Interface and its methods. We will explain the purpose of all the methods with an example. Basically, Servlet Interface contains five methods which are described below. Before discussing its methods let's first understand about Servlet interface.

What is the Servlet Interface?

All the servlet 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. A method is also provided that allows a servlet to obtain any initialization parameters.

Read: How to get HTML form data in Servlet

Servlet Interface 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. An UnavailableException should be thrown if the servlet cannot be initialized.
If you, don't know about the exception I will recommend you to first learn
What is Exception?

2) public void service(ServletRequest req,ServletResponse res) throws ServletException, IOException: 

The Service() method is called to process a request from a client. The request from a client can be read from req. The response to the client can be written to res. An Exception is generated if some IO and Servlet problems occur.

3) public void destroy():

The server calls the destroy() method after the servlet has been taken out of service and all pending requests to the servlet have completed or time out.

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.

Example of Servlet Interface:

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

Web.xml file:
Servlet interface

Servlet interface

Servlet interface and its methods explained with example Servlet interface and its methods explained with example Reviewed by Prashant Srivastava on October 13, 2018 Rating: 5

No comments:

Powered by Blogger.