GenericServlet Class

Java provides an alternative way to create a servlet in the form of GenericServlet. It is an abstract class present in javax.servlet package that implements Servlet, ServletConfig and Serializable interface. So, now our servlet program needs to extend GenericServlet. Although we are still using the servlet interface indirectly. This is an easier way to a create servlet because in this approach we required to provide the declaration of service() method only. GenericServlet class is protocol dependent as it is capable of handling any type of request. GenericServlet program using HTML In this program HTML code is also used within Servlet. GenericExample.java

import java.io.*;
import javax.servlet.*;
public class GenericExample extends GenericServlet
{
	public void service(ServletRequest req, ServletResponse res) throws ServletException,IOException
	{
		res.setContentType("text/html");
		PrintWriter pw=res.getWriter();
		pw.println("<html><body>");
		pw.println("<h1>Hello Servlet</h1>");
		pw.println("</body></html>");	
	}
}
web.xml Now deploy your servlet in web.xml file.
<web-app>
  <servlet>
  <servlet-name>GenericExample</servlet-name>
  <servlet-class>GenericExample</servlet-class>
  <servlet>
  <servlet-mapping>
  <servlet-name>GenericExample</servlet-name>
  <url-pattern>/GenericExample</url-pattern>
  </servlet-mapping>  
</web-app>
Output: