2.3K
Generic Class Methods
Table of Contents
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. | Methods | Description |
1 | public void init(ServletConfig config) | It is used to initialize the servlet. |
2 | public 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. |
3 | public void destroy() | It is invoked only once throughout the life cycle and indicates that servlet is being destroyed. |
4 | public ServletConfig getServletConfig() | It returns the object of ServletConfig. |
5 | public String getServletInfo() | It 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() | It returns the object of ServletContext. |
8 | public String getInitParameter(String name) | It returns the parameter value for the given parameter name. |
9 | public Enumeration getInitParameterNames() | It returns all the parameters defined in the web.xml file. |
10 | public String getServletName() | It returns the name of the servlet object. |
11 | public void log(String msg) | It writes the given message in the servlet log file. |
12 | public void log(String msg,Throwable t) | It writes the explanatory message in the servlet log file and a stack trace. |
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>");
}
}