Servlet Interface -


We can create web applications in java in 3 ways -

1- By implementing Servlet Interface.
2- By extending GenricServlet class.
3- By extending HttpServlet class.

javax.servlet.Servlet Interface -

Servlet interface defines the methods that a class should implement to create a servlet. It defines methods to create a servlet, to serve the client request, and to destroy the servlet.

Methods of Servlet Interface -

1- init() - It is used to initialize a servlet. It is called only once in servlet life time and it must complete before any call to service() is made i.e. it must complete before any request came to servlet.
It has the following syntax -
public void init(ServletConfig config) throws ServletException
Here config is a ServletConfig object that contains servlet configuration and initialization parameters information.
2- getServletConfig() - It is used to get the ServletConfig object. It can be used by servlet to get the initialization parameters and configuration information. It is the same object that we pass in init() method.
It has the following syntax -
public ServletConfig getServletConfig()
It returns the ServletConfig object.
3- service() - It generate the response for client request. It is called each time when a request is made for the servlet.
It has the following syntax -
public void service(ServletRequest request, ServletResponse response)throws ServletException, IOException
Where - 
request - is a ServletRequest object that contain request made by client.
response - is a ServletResponse object that contain response generated by servlet for the coming request.
4- getServletInfo() - It returns the information about the servlet such as writer name, copyright, version etc.
It has the following syntax -
public String getServletInfo()  
It return the servlet information as String object.  
5- destroy() - It is called just before Servlet destroyed. It allows us to do some work that we want to do before Servlet has destroyed (for example closing a stream).After destoy(), Servlet becomes eligible for garbage collection.
It has the following syntax -
public void destroy()        

Example -

This example will show you how to create servlet using Servlet Interface.

1- Using NetBeans IDE -

Create a Java Web, Web Application Project in NetBeans.(Here we are using NetBeans IDE 8.2)
Note- If you are new to NetBeans IDE and do not know how to create Web Applications in NetBeans, then please refer to given link to learn how to download, install NetBeans IDE and how to create and run your first java web application - How to download and install NetBeans setup, and run your First Web Application.
Here we have given the name of project - 'ServletInterfaceDemo' It will create the following project structure -



Now you have to follow the following steps -
1- index.html - As shown in above figure 'Web Pages' folder contains a file named 'index.html', It will be your default page(i.e. when you run your project, the output of this page will be displayed.).
Note- If you are using older version of NetBeans then your default page will be 'index.jsp'
Make changes to index.html as shown below -

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <a href="test">Click here to go to servlet</a>
    </body>
</html>
       
2- Create a package named 'servs' in 'Source Packages' folder, then create a new class named MyFirstServ within that package as shown below -



Add the following code to 'MyFirstServ' class -
package servs;

import java.io.*;
import javax.servlet.*;

public class MyFirstServ implements Servlet
{
    
private ServletConfig sc;   
    
 public void init(ServletConfig config)throws ServletException
 {
     sc = config;
 }
 
 public ServletConfig getServletConfig()
 {
     return sc;
 }
 
 public void service(ServletRequest request, ServletResponse response)throws ServletException,IOException
 {
     try
     {
         response.setContentType("text/html");      // Infrom client browser what type of data is coming in response.
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         out.println("<title>My FIrst Servlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>Welcome to Servlet</h1>");
         out.println("</body>");
         out.println("</html>");
     }
     catch(Exception ex)
     {
         System.out.println(ex);
     }
 }
 
 public String getServletInfo()
 {
     return "Info";
 }
 
 public void destroy()
 {
     
 }
}    
Program Description -
  • To convert 'MyFirstServ' class into servlet, class implements 'Servlet' interface. As we allrady know Servlet interface contains 5 methods, so override these methods.
  • Except service() method, all the remaining 4 methods have the same above implementation in all programs.
  • Note that Servlet's do not have main() method, Whenever request came to servlet, it is the service() method that gets executed. So service() method will change in all program according to your requirements. Whatever output produced by servlet will be the output of your service() method. In this example it creates a simple html page with output 'Welcome to Servlet'.
  • service() method has 2 parameters- ServletRequest request and ServletResponse response - these corresponds to client request and response generated by server for the coming request.
  • response.setContentType("text/html"); - ServletResponse has method setContentType() that inform the client browser, what type of data is coming in response from server, so that browser can do the right things, for example launch a helper app like video player or pdf reader etc.
  • PrintWriter out = response.getWriter(); - java.io.PrintWriter object is required to write HTML text , we can get it from ServletResponse.
  • out.println() - PrintWriter has print() and println() methods that are used to write HTML text on web pages.

3- web.xml (Deployment Descriptor) -
  • When we deploy our application on server, we need to create a XML file (web.xml), to tell the server, how to run our Servlet,s. This web.xml file is also called Deployment Desciptor.
  • In this file we have to put all the information regarding our servlets like servlet name, servlet class, url etc. Basically the main purpose of this is to create a mapping between client known public url('test' in our example) and servlet class name('MyFirstServ' in our example).
  • In addition to servlet information , web.xml file also used to contain several other information that will be discussed ahead.
To add Web.XML in your project, follow the following steps -
` Right click on your project go to New -> Other, It will open a window as shown below -


Click Next -> Finish, and it will create a web.xml file in Configuration Files as shown below -



For mapping client known public url('test' in our example) and servlet class name('MyFirstServ' in our example), we need to define following 2 XML tags -
<servlet>
It maps internal name defined in web.xml to your original servlet class name.
It contains two sub tags within it -
1- <servlet-name> - It contain internal name defined in web.xml (We used 'demo' in our example). This name can be anything, whatever you want.
2- <servlet-class> - It contain fully qualified servlet class name with package name ('servs.MyFirstServ' in our example).
<servlet>
   <servlet-name>demo</servlet-name>
   <servlet-class>servs.MyFirstServ</servlet-class>
</servlet>   
<servlet-mapping>
It maps internal name defined in web.xml to client known public url. It contains two sub tags within it -
1- <servlet-name> - It will be the same as we defined in <servlet> tag(i.e. demo in our example). 2- <url-pattern> - It will be the client known public url ('/test' in our example, because in index.html we use 'test' as hyperlink in anchor tag).
<servlet-mapping>
  <servlet-name>demo</servlet-name>
  <url-pattern>/test</url-pattern>
</servlet-mapping>         
Add the above defined both tags in web.xml within web-app as follows -
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	 version="3.1">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    
    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>servs.MyFirstServ</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
    
</web-app>  

4- Now run your project and it will show you the default page (index.html) on your web browser as follows -



Click on the link and it will show you the following output -

2- Using Eclipse IDE -

Create a New Dynamic Web Project in Eclipse.(Here we are using Eclipse Oxygen IDE)
Note- If you are new to Eclipse IDE and do not know how to create Web Applications in Eclipse, then please refer to given link to learn how to download, install Eclipse IDE and how to create and run your first java web application - How to download and install Eclipse setup, and run your First Web Application.
Here we have given the name of project - 'ServletInterfaceDemo'.
It will create the following project structure -



Now you have to follow the following steps -
1- index.html - Right Click on your Project and add a 'index.html' page. And add the following code -
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="test">Click here to go to servlet</a>
</body>
</html>        
2- Create a package named 'servs' in 'src' folder, then create a new class named MyFirstServ within that package as shown below -



Add the following code to 'MyFirstServ' class -
package servs;

import java.io.*;
import javax.servlet.*;

public class MyFirstServ implements Servlet
{
    
private ServletConfig sc;   
    
 public void init(ServletConfig config)throws ServletException
 {
     sc = config;
 }
 
 public ServletConfig getServletConfig()
 {
     return sc;
 }
 
 public void service(ServletRequest request, ServletResponse response)throws ServletException,IOException
 {
     try
     {
         response.setContentType("text/html");     
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         out.println("<title>My FIrst Servlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>Welcome to Servlet</h1>");
         out.println("</body>");
         out.println("</html>");
     }
     catch(Exception ex)
     {
         System.out.println(ex);
     }
 }
 
 public String getServletInfo()
 {
     return "Info";
 }
 
 public void destroy()
 {
     
 }
}    
Program Description -
  • To convert 'MyFirstServ' class into servlet, class implements 'Servlet' interface. As we already know Servlet interface contains 5 methods, so override these methods.
  • Except service() method, all the remaining 4 methods have the same above implementation in all programs.
  • Note that Servlet's do not have main() method, Whenever request came to servlet, it is the service() method that gets executed. So service() method will change in all program according to your requirements. Whatever output produced by servlet will be the output of your service() method. In this example it creates a simple html page with output 'Welcome to Servlet'.
  • service() method has 2 parameters- ServletRequest request and ServletResponse response - these corresponds to client request and response generated by server for the coming request.
  • response.setContentType("text/html"); - ServletResponse has method setContentType() that inform the client browser, what type of data is coming in response from server, so that browser can do the right things, for example launch a helper app like video player or pdf reader etc.
  • PrintWriter out = response.getWriter(); - java.io.PrintWriter object is required to write HTML text , we can get it from ServletResponse.
  • out.println() - PrintWriter has print() and println() methods that are used to write HTML text on web pages.

3- web.xml (Deployment Descriptor) -
  • When we deploy our application on server, we need to create a XML file (web.xml), to tell the server, how to run our Servlet,s. This web.xml file is also called Deployment Descriptor.
  • In this file we have to put all the information regarding our servlets like servlet name, servlet class, url etc. Basically the main purpose of this is to create a mapping between client known public url('test' in our example) and servlet class name('MyFirstServ' in our example).
  • In addition to servlet information , web.xml file also used to contain several other information that will be discussed ahead.
For mapping client known public url('test' in our example) and servlet class name('MyFirstServ' in our example), we need to define following 2 XML tags -
<servlet>
It maps internal name defined in web.xml to your original servlet class name.
It contains two sub tags within it -
1- <servlet-name> - It contain internal name defined in web.xml (We used 'demo' in our example). This name can be anything, whatever you want.
2- <servlet-class> - It contain fully qualified servlet class name with package name ('servs.MyFirstServ' in our example).
<servlet>
   <servlet-name>demo</servlet-name>
   <servlet-class>servs.MyFirstServ</servlet-class>
</servlet>   
<servlet-mapping>
It maps internal name defined in web.xml to client known public url.It contains two sub tags within it -
1- <servlet-name> - It will be the same as we defined in <servlet> tag(i.e. demo in our example). 2- <url-pattern> - It will be the client known public url ('/test' in our example, becaue in index.html we use 'test' as hyperlink in anchor tag).
<servlet-mapping>
  <servlet-name>demo</servlet-name>
  <url-pattern>/test</url-pattern>
</servlet-mapping>         
Add the above defined both tags in web.xml within web-app as follows -
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<display-name>ServletInterfaceDemo</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	  <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>servs.MyFirstServ</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>

4- Now run your project and it will show you the default page (index.html) on your web browser as follows -



Click on the link and it will show you the following output -