Servlet interface in java

Servlet interface:

Servlet interface contains the common methods for all servlets i.e. provides the common behaviour for all servlets.

public interface Servlet

Servlet interface is in javax.servlet package (javax.servlet.Servlet).

Methods of servlet interface:

1. init(ServletConfig config): It is used to initialize the servlet. This method is called only once by the web container when it loads the servlet.

public void init(ServletConfig config)throws ServletException

2. service(ServletRequest request,ServletResponse response): It is used to respond to a request. It is called for every new request by web container.

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

3. destroy(): It is used to destroy the servlet. This method is called only once by the web container when all threads of the servlet have exited or in a timeout case.

public void destroy()

4. getServletConfig(): It returns a servlet config object. This config object is passed in init method.  Servlet config object contains initialization parameters and startup configuration for this servlet.

public ServletConfig getServletConfig()

5. getServletInfo(): It returns a string of information about servlet’s author, version, and copyright etc.

public String getServletInfo()

Servlet “Hello World” example by implementing Servlet interface.

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
 * This servlet program is used to print "Hello World" on 
 * client browser by implementing servlet interface.
 * @author w3spoint
public class HelloWorld implements Servlet {
    private static final long serialVersionUID = 1L;
    //no-argument constructor.
    public HelloWorld() {
    ServletConfig config=null;
    public void init(ServletConfig config) throws ServletException {
    	this.config = config;
    	System.out.println("Do initialization here.");		
    public void destroy() {
	System.out.println("Do clean-up process here.");
    public ServletConfig getServletConfig() {
       	return config;
    public String getServletInfo() {
	return "";
    public void service(ServletRequest request, ServletResponse response)
		throws ServletException, IOException {
	PrintWriter out = response.getWriter();
        out.println("<h1>Hello World example using " +
   		"servlet interface.</h1>");


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" 


servlet example 1
Download this example.
Next Topic: GenericServlet class in java with example.
Previous Topic: Life cycle of a servlet.


Please Share