Java.Servlet.Why is the HttpServlet class declared as abstract?

Because it is designed to be extended, not used directly.

  • HttpServlet provides basic HTTP-specific functionality:
    • It implements the service() method to automatically dispatch requests based on the HTTP method (GET, POST, PUT, DELETE, etc.).
  • But it does not know what your application logic should do in doGet(), doPost(), etc.

👉 So the framework says:

“Hey developer, I’ll take care of the boring stuff.
You just override the methods you care about!”

Thus, it’s declared abstract to force you to create your own subclass and implement specific behavior.

🎯 What Happens Internally

✅ In HttpServlet:

  • service() is implemented like this (simplified):
protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String method = req.getMethod();

    if (method.equals("GET")) {
        doGet(req, resp);
    } else if (method.equals("POST")) {
        doPost(req, resp);
    }
    // etc.
}
  • But doGet(), doPost(), etc. are empty by default!

Example of default doGet() inside HttpServlet:

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "GET not supported");
}

➡️ So if you don’t override doGet(), your servlet will respond with 405 Method Not Allowed!

🚀 In short:

ReasonWhy
HttpServlet is abstractBecause it expects you to extend it and provide your own business logic
Default behaviorProvides structure but no meaningful handling for any HTTP method
Prevents misuseYou can’t accidentally create a servlet that does nothing or breaks protocol
Template patternFollows the Template Method design pattern — defines skeleton, subclasses customize specific steps

🛠️ Real-world analogy:

Think of HttpServlet like a blueprint for a house:

  • It defines the layout (doors, windows, rooms).
  • But YOU decide the interior design (colors, furniture, decorations).

⚡ Quick Summary:

ConceptHttpServlet
Abstract?✅ Yes
Why abstract?Forces you to override doGet(), doPost(), etc. to add real behavior
Provides default service()?✅ Yes, dispatches based on HTTP method
Provides default doGet(), doPost()?✅ Yes, but default is error (you must override)
PatternTemplate Method Pattern
This entry was posted in Без рубрики. Bookmark the permalink.