Return to site

🧩🌐 OVERRIDING service() IN A SERVLET: WHAT REALLY HAPPENS?

· jakartaee
Section image

🔸 TLDR

If you override service() and don’t manually forward to doGet() / doPost(), your servlet won’t dispatch requests — even for GET. 🛑

🔸 QUICK CONTEXT

In a classic HttpServlet, the built-in service() method routes the request to the right handler (doGet, doPost, …).

But if you override service(), you can accidentally stop that routing. 🚦

🔸 THE QUIZ

You have a servlet with these two methods:

▪️ service(req, res) writes: "Service() method called."

▪️ doGet(req, res) writes: "Get() method called."

Now the servlet receives a GET request.

👉 What response text will the client get?

▪️ Service() method called.

▪️ Service() method called. Get() method called.

▪️ An HTTP error

▪️ Get() method called.

🔸 ANSWER (CHECK YOURSELF) ✅

▪️ Service() method called.

🔸 WHY?

When you override service(), you replace the default routing logic that normally calls doGet() for GET requests.

So the container calls your service()… and stops there.

➡️ doGet() is never reached.

🔸 TAKEAWAYS

▪️ HttpServlet#service() is the dispatcher (GET → doGet, POST → doPost, etc.).

▪️ Overriding service() usually breaks that dispatcher unless you re-implement it.

▪️ Prefer overriding doGet() / doPost() for normal web endpoints.

▪️ Only override service() for advanced cases (custom routing, cross-cutting concerns), and call super.service(req, res) when appropriate.

#Java #Servlet #JakartaEE #JavaWeb #BackendDevelopment #SoftwareEngineering #CodingInterview #JavaCertification #WebDevelopment #DevTips

Go further with Java certification:

Java👇

Spring👇

SpringBook👇

JavaBook👇