Java Notes
Understanding GenericServlet abstract class in Java - protocol-independent servlet implementation, methods, and comparison with HttpServlet.
What is GenericServlet?
GenericServlet is an abstract class in the jakarta.servlet package that provides a protocol-independent implementation of the Servlet interface. It handles the boilerplate of servlet configuration, leaving you to implement only the service() method.
Why GenericServlet Exists
Without GenericServlet, you'd have to implement ALL Servlet interface methods:
// ❌ Without GenericServlet — too much boilerplate
public class MyServlet implements Servlet {
private ServletConfig config;
public void init(ServletConfig config) { this.config = config; }
public ServletConfig getServletConfig() { return config; }
public void service(ServletRequest req, ServletResponse resp) { }
public String getServletInfo() { return ""; }
public void destroy() { }
}
// ✅ With GenericServlet — only implement service()
public class MyServlet extends GenericServlet {
public void service(ServletRequest req, ServletResponse resp)
throws ServletException, IOException {
resp.getWriter().println("Hello World");
}
}GenericServlet Methods
| Method | Description |
|---|---|
init(ServletConfig) | Called by container; stores config |
init() | Convenience init — override this one |
service(ServletRequest, ServletResponse) | Abstract — you must implement |
destroy() | Cleanup hook |
getServletConfig() | Returns stored ServletConfig |
getServletContext() | Returns application context |
getInitParameter(String) | Get init parameter value |
getInitParameterNames() | Get all param names |
getServletInfo() | Returns servlet description |
getServletName() | Returns servlet name |
log(String) | Write to servlet log |
Complete GenericServlet Example
package com.example;
import jakarta.servlet.*;
import java.io.*;
public class WelcomeServlet extends GenericServlet {
private String welcomeMessage;
@Override
public void init() throws ServletException {
// Read initialization parameter
welcomeMessage = getInitParameter("message");
if (welcomeMessage == null) {
welcomeMessage = "Welcome to our application!";
}
log("WelcomeServlet initialized with message: " + welcomeMessage);
}
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = request.getParameter("name");
out.println("<html>");
out.println("<head><title>Welcome</title></head>");
out.println("<body>");
out.println("<h1>" + welcomeMessage + "</h1>");
if (userName != null) {
out.println("<p>Hello, " + userName + "!</p>");
}
out.println("<p>Server: " + getServletInfo() + "</p>");
out.println("</body>");
out.println("</html>");
}
@Override
public String getServletInfo() {
return "WelcomeServlet v1.0 by WohoTech";
}
@Override
public void destroy() {
log("WelcomeServlet destroyed");
}
}web.xml Configuration
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>com.example.WelcomeServlet</servlet-class>
<init-param>
<param-name>message</param-name>
<param-value>Welcome to WohoTech!</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>GenericServlet vs HttpServlet
| Feature | GenericServlet | HttpServlet |
|---|---|---|
| Package | jakarta.servlet | jakarta.servlet.http |
| Protocol | Any protocol | HTTP-specific |
| Abstract method | service() | None (but override doGet/doPost) |
| Request type | ServletRequest | HttpServletRequest |
| Response type | ServletResponse | HttpServletResponse |
| HTTP methods | Not supported | doGet, doPost, doPut, doDelete |
| Session support | No | Yes |
| Usage | Rarely used | Always used in web apps |
When to Use GenericServlet
- Building non-HTTP protocol handlers (rare)
- Learning the servlet architecture from basics
- Creating protocol-independent service components
In real-world applications, you'll almost always extend HttpServlet instead.
Source Code of GenericServlet (Simplified)
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
private transient ServletConfig config;
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init(); // calls your convenience init()
}
public void init() throws ServletException {
// Override this for custom initialization
}
public abstract void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;
public void destroy() {
// Override for cleanup
}
public ServletConfig getServletConfig() {
return config;
}
public ServletContext getServletContext() {
return config.getServletContext();
}
public String getInitParameter(String name) {
return config.getInitParameter(name);
}
public void log(String message) {
getServletContext().log(getServletName() + ": " + message);
}
}Key Interview Points
- GenericServlet is abstract — cannot be instantiated directly
- It implements both
ServletandServletConfiginterfaces - Only
service()is abstract — everything else has default implementations - The two-arg
init(ServletConfig)calls the no-arginit() - Always override the no-arg
init()to avoid forgettingsuper.init(config) - GenericServlet is protocol-independent — not tied to HTTP
- In practice, HttpServlet (which extends GenericServlet) is used for web applications
🔥 Interview Questions
Q1. What is GenericServlet?
Answer: GenericServlet is an abstract class that implements the Servlet interface. It is protocol-independent — you can create servlets for any protocol (HTTP, FTP, etc.). HttpServlet extends GenericServlet for HTTP-specific functionality.
Q2. What is the difference between GenericServlet and HttpServlet?
Answer:
| Feature | GenericServlet | HttpServlet |
|---|---|---|
| Protocol | Any protocol | HTTP only |
| Method | service() | doGet(), doPost(), etc. |
| Abstract | service() is abstract | service() dispatches to doXxx() |
| Use case | Non-HTTP protocols | Web applications (99% cases) |
Q3. What is the role of the service() method in GenericServlet?
Answer: The service() method is called on every request. In GenericServlet it is abstract — implementing it in the subclass is mandatory. In HttpServlet it is already implemented and checks the HTTP method to call the appropriate doGet()/doPost().
Q4. What are the important methods of GenericServlet?
Answer: init(ServletConfig) - initialization, service(ServletRequest, ServletResponse) - request handling, destroy() - cleanup, getServletConfig() - configuration access, getServletInfo() - servlet description, getInitParameter() - init params access.
Q5. Do we still use GenericServlet today?
Answer: Practically no — 99% of web servlets extend HttpServlet because web development is based on the HTTP protocol. GenericServlet is only relevant for educational purposes or non-HTTP protocols. Understanding the hierarchy is important for interviews.
Q6. What are the two versions of the init() method in GenericServlet?
Answer: init(ServletConfig config) — called by the container, stores the ServletConfig. init() (no-arg) — a convenience method that subclasses can override without calling super.init(config). Overriding the no-arg version is recommended for custom initialization.
Q7. ServletRequest vs HttpServletRequest?
Answer: ServletRequest is a generic protocol-independent interface (used with GenericServlet). HttpServletRequest adds HTTP-specific methods: getMethod(), getHeader(), getSession(), getCookies(), etc. In HttpServlet, the request is automatically HttpServletRequest.
Q8. How many methods of the Servlet interface does GenericServlet implement?
Answer: Implements 4 out of 5 methods of the Servlet interface (init, destroy, getServletConfig, getServletInfo). The service() method remains abstract — the subclass must implement it.
Q9. Can GenericServlet be directly instantiated?
Answer: No — it is an abstract class (service() is abstract). A subclass that implements service() must be created. The container (Tomcat) instantiates the subclass.
Q10. Explain the Servlet hierarchy.
Answer: Servlet (interface) → GenericServlet (abstract class, implements Servlet) → HttpServlet (abstract class, extends GenericServlet) → MyServlet (concrete class, extends HttpServlet). Specificity increases from top to bottom.
Summary
GenericServlet provides a convenient base class that eliminates boilerplate code. While rarely used directly in modern web development, understanding it helps you grasp how HttpServlet works internally since HttpServlet extends GenericServlet.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for GenericServlet.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, servlets, jsp, generic
Related Java Master Course Topics