Home Java Tutorial GenericServlet

GenericServlet

by anupmaurya
11 minutes read

In this tutorial, you’ll learn about GenericServlet, Methods of GenericServlet class , Servlet Example by inheriting the GenericServlet class and more.

What is GenericServlet

  • A generic servlet is a protocol-independent as GenericServlet class can handle any type of request.
  • Servlet should always override the service() method to handle the client request.
  • The service() method accepts two arguments ServletRequest object and ServletResponse object. The request object tells the servlet about the request made by the client while the response object is used to return a response back to the client.

You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method.

Methods of GenericServlet class

There are many methods in GenericServlet class. They are as follows:

S.No.MethodsDescription
1public void init(ServletConfig config)It is used to initialize the servlet.
2public abstract void service(ServletRequest request, ServletResponse response)It provides service for the incoming request. It is invoked at each time when user requests for a servlet.
3public void destroy()It is invoked only once throughout the life cycle and indicates that servlet is being destroyed.
4public ServletConfig getServletConfig()It returns the object of ServletConfig.
5public String getServletInfo() It returns information about servlet such as writer, copyright, version etc.
6public void init()It is a convenient method for the servlet programmers, now there is no need to call super.init(config)
7public ServletContext getServletContext()It returns the object of ServletContext.
8public String getInitParameter(String name)It returns the parameter value for the given parameter name.
9public Enumeration getInitParameterNames()It returns all the parameters defined in the web.xml file.
10public String getServletName()It returns the name of the servlet object.
11public void log(String msg)It writes the given message in the servlet log file.
12public void log(String msg,Throwable t) It writes the explanatory message in the servlet log file and a stack trace.
Generic Class Methods

Servlet Example by inheriting the GenericServlet class

import java.io.*;  
import javax.servlet.*;  
  
public class First extends GenericServlet{  
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>hello generic servlet</b>");  
out.print("</body></html>");  
  
}  

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.