As of now, we have discussed Servlet Interface, ie. to create servlet by implementing Servlet Interface. Also, I have told you in the previous document there are two ways in which we can create servlet.
By directly implementing the servlet Interface (we have seen earlier), Now in this document, we will discuss By extending the GenericServlet class.
What is GenericServlet?
GenericServlet is a class that implements the Servlet Interface. It not only implement servlet Interface but also implements serializable and ServletConfig Interface. It is a protocol-independent class that means it can handle any type of request. In order to write GenericServlet, we need to override only the service() method.
How GenericServlet works?
GenericServlet is an abstract class and has only one method which is service(). Its working is the same as that of the servlet only the difference here is we don’t need to override all the methods of the life-cycle of the servlet. In this, we just override the service() method and it will handle the request and give us the response.
Advantages of GenericServlet
- GenericServlet is easier to write.
- To write it we just need to extend the class and override service() methods.
Disadvantages of GenericServlet
- It is not convenient to use the GenericServlet class.
- It is not a safe approach to use Generic Servlet.
Methods in GenericServlet class
- public void init(ServletConfig config): This method is used to initialize the servlet.
- config: It contains servlet startup information and initialization parameters.
- public abstract void service(ServletRequest req, ServletResponse res): It handles the incoming request and gives back the response to the client.
- req: request from the client.
- res: response to the client.
- public void destroy(): It indicates that the servlet is destroyed.
- public ServletConfig getServletConfig():This method returns the object of ServletConfig.
- public String getServletInfo(): This method returns information about the servlet like an author, version, etc.
- public ServletContext getServletContext():This method returns the object of servlet context.
- public String getInitParameters(String name): This method returns the parameter value for the parameter name.
- public Enumeration getInitParameterNames():This method returns all the parameters value which is in web.xml file. (WEB.xml file we will discuss it ahead)
- public String getServletName():This method returns name of servlet.
- public void log(String name): This method writes the message to log.
- public void log(String msg, Throwable tw): This method writes the explanatory message to log.
Let’s see the Example for GenericServlet
In this example, We have created our Servlet(GenericExample.java) which extends the GenericServlet.