🧠 First: What are GenericServlet
and HttpServlet
?
Class | Meaning |
---|---|
GenericServlet | An abstract class designed for any type of protocol (not just HTTP). |
HttpServlet | A concrete class specifically for HTTP protocol (GET, POST, PUT, DELETE, etc.). |
Both help you avoid writing Servlet API code from scratch — they implement some boring methods for you already.
🎯 Key Differences Between GenericServlet
and HttpServlet
Feature | GenericServlet | HttpServlet |
---|---|---|
Designed for | Generic protocols (could be HTTP, FTP, SMTP, etc.) | HTTP protocol only |
Direct subclass of | Servlet interface | GenericServlet |
Supports HTTP methods like GET, POST? | ❌ No (you implement service() manually) | ✅ Yes (provides doGet() , doPost() , etc.) |
Default service() method? | You must override service(ServletRequest, ServletResponse) yourself | Already implemented; dispatches automatically to doGet() , doPost() , etc. |
Typical usage | Very rare (custom protocols, non-HTTP servers) | Very common (web applications) |
Simplifies | Basic Servlet lifecycle | Full HTTP request/response handling |
⚙️ How You Use Them (Code Examples)
✅ Using GenericServlet
(You must override service()
and manually check protocol yourself if needed)
public class MyGenericServlet extends GenericServlet {
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
response.getWriter().println("Hello from GenericServlet");
}
}
- No help with HTTP headers, status codes, etc.
- Very low-level.
✅ Using HttpServlet
(You override doGet()
, doPost()
, etc., and server handles routing)
public class MyHttpServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
response.getWriter().println("Hello from HttpServlet via GET!");
}
}
- Much easier.
- Server automatically calls
doGet()
if browser sends GET,doPost()
for POST, etc.
🔥 Quick Memory Trick
If you think | Then |
---|---|
“I want to work with HTTP requests, methods, sessions, cookies.” | Use HttpServlet |
“I’m building something not tied to HTTP (rare!)” | Use GenericServlet |
⚡ Quick Recap in 5 Sec:
GenericServlet
: generic, you handle everything yourself.HttpServlet
: HTTP-focused, gives you ready-to-usedoGet()
,doPost()
,doPut()
,doDelete()
, etc.
In real life → almost always use HttpServlet
unless you are building a custom protocol server (which is super rare).