GenericServlet -


GenericServlet -

javax.servlet.GenericServlet is an abstract class that implements the Servlet Interface and override its all methods except service() method. So it makes easier to create servlet as we need to override service() method only.
GenericServlet,s are protocol independent and not specific to HTTP protocol. However it is general practice to use protocol specific class(HttpServlet).

Fig: Generic Servlet implements all methods of Servlet except service() method


Example -

This example will show you how to create servlet using GenericServlet class.

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 - 'GenericServletDemo' 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 Genric 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 extends GenericServlet
{
 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);
     }
 }  
}
    
Program Description -
  • To convert 'MyFirstServ' class into servlet, class extends 'GenericServlet' class. As we allrady know GenericServlet provides implementation of all the methods of Servlet interface except service(), So here we only need to override service() method.
  • 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.
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 - 'GenericServletDemo'.
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 Genric 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 extends GenericServlet
{
 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);
     }
 }  
}
    
Program Description -
  • To convert 'MyFirstServ' class into servlet, class extends 'GenericServlet' class. As we already know GenericServlet provides implementation of all the methods of Servlet interface except service(), So here we only need to override service() method.
  • 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, 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 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>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 -