GenericServlet class

GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface.

GenericServlet class defines a generic protocol independent servlet. It is protocol independent in the sense it can be extended to provide implementation of any protocol like FTP, SMTP etc.

Constructor:

  • public GenericServlet() Does nothing. All of the servlet initialization is done by one of the init methods

Methods of GenericServlet class

There are many methods in GenericServlet class.

  1. public void init(ServletConfig config) is used to initialize the servlet.
  2. public abstract void service(ServletRequest request, ServletResponse response) provides service for the incoming request. It is invoked at each time when user requests for a servlet.
  3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being destroyed.
  4. public ServletConfig getServletConfig() returns the object of ServletConfig.
  5. public String getServletInfo() returns information about servlet such as writer, copyright, version etc.
  6. public void init() it is a convenient method for the servlet programmers, now there is no need to call super.init(config)
  7. public ServletContext getServletContext() returns the object of ServletContext.
  8. public String getInitParameter(String name) returns the parameter value for the given parameter name.
  9. public Enumeration getInitParameterNames() returns all the parameters defined in the web.xml file.
  10. public String getServletName() returns the name of the servlet object.
  11. public void log(String msg) writes the given message in the servlet log file.
  12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log file and a stack trace.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
	public class GenericServletExample extends GenericServlet 
	{
	public void init()
		{
			log("inside init() method");
		}
		public void service(ServletRequest request, ServletResponse response) 
		throws ServletException, IOException
		{
			log("Handling request");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.write("<html>"<head>"<title>GenericServlet example"</title>"</head>");
			out.write("<body><h1>GenericServlet: Welcome to all "</h1>"</body>"</html>");
		out.close();
	}
	public void destroy() 
	{
		log("inside destroy() method");
	}
	}