Java.Servlet.What are the differences between GenericServlet and HttpServlet?

🧠 First: What are GenericServlet and HttpServlet?

ClassMeaning
GenericServletAn abstract class designed for any type of protocol (not just HTTP).
HttpServletA 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

FeatureGenericServletHttpServlet
Designed forGeneric protocols (could be HTTP, FTP, SMTP, etc.)HTTP protocol only
Direct subclass ofServlet interfaceGenericServlet
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) yourselfAlready implemented; dispatches automatically to doGet(), doPost(), etc.
Typical usageVery rare (custom protocols, non-HTTP servers)Very common (web applications)
SimplifiesBasic Servlet lifecycleFull 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 thinkThen
“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-use doGet(), doPost(), doPut(), doDelete(), etc.

In real life → almost always use HttpServlet unless you are building a custom protocol server (which is super rare).

This entry was posted in Без рубрики. Bookmark the permalink.