In this tutorial you will learn about the Servlet Interface and its application with practical example.
Servlet Interface
A Servlet is small program which runs within a web server and public interface Servlet defines methods which is must implemented by all Servlet. For initialization a Servlet, For service requests and for removing a Servlet from the server this interface defines some methods. These methods are called life-cycle methods. Also it provides 2 non-life-cycle methods.
Servlet Interface Methods
These are 5 life-cycle and non-life-cycle methods in Servlet Interface.
public void init(ServletConfig config) :– This method is called by the Servlet container which indicates that Servlet is being placed into service. The Servlet container calls the init method only once post instantiating the Servlet. This is life-cycle method of Servlet.
public void service(ServletRequest request,ServletResponse response) :-
This method is called by the Servlet container which is used to allow the Servlet to respond to a request. This method is called post the init() method of Servlet.
public ServletConfig getServletConfig() :-
This method returns a ServletConfig object, which contains initialization and startup parameter for this Servlet.
public String getServletInfo() :– This method returns information about the Servlet, like author, version, and copyright. The string that this methods returns must be plain text.
public void destroy():- If the Servlet taken out from the service so this method is being called by the Servlet container. After calling method by Servlet container, it will not call the service method again on this Servlet.
Example:-
Let’s understand these all methods and Servlet Interface By below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.io.*; import javax.servlet.*; public class InterfaceExample implements Servlet { ServletConfig config = null; public void init(ServletConfig config) { this.config = config; System.out.println("W3adda : Servlet is initialized"); } public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.print("<html><body>"); out.print("<b><h2>W3 Adda : Servlet Interface Example</h2></b>"); out.print("</body></html>"); } public void destroy() { System.out.println("W3Adda : Servlet is Destroyed"); } public ServletConfig getServletConfig() { return config; } public String getServletInfo() { return "W3Adda: Copyright 2017-2018"; } } |
Output:-
Output of this class will be like below image.