I was reading a book on servlets, in that book a brief explanation is given about the servlet class, as well as the HttpServlet
class.
There is one exam
The service() method belongs to Genericservlet and can be overloaded to support any type of protocol such as Http,Ftp etc.
Then you have specialized servlet for handling HttpProtocol, we call it HttpServlet. The HttpServlet also provides default implementation for service() and doGet() and doPost() methods.
Why we should not override the service() method?
Since It's not a good practice to override the service method. If we call any of the doxxx method then internally it will call the service method of the HttpServlet. So there's no need for you to call it explicitly.
Order of Execution of service():
service(ServletRequest,ServletResponse)-->
-->calls
-->service(HttpServletRequest req,HttpServletResponse res)
-->calls
-->doGet/doPost(HttpServletRequest req,HttpServletResponse res)
This is how you can override the service in case you want to:
protected void service(HttpServletRequest req, HttpServletResponse resp) {
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
doGet(req, resp);
} else if (method.equals(METHOD_HEAD)) {
doHead(req, resp);
} else if (method.equals(METHOD_POST)) {
doPost(req, resp);
} else if (method.equals(METHOD_PUT)) {
doPut(req, resp);
} else if (method.equals(METHOD_DELETE)) {
doDelete(req, resp);
} else if (method.equals(METHOD_OPTIONS)) {
doOptions(req,resp);
} else if (method.equals(METHOD_TRACE)) {
doTrace(req,resp);
} else {
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}}
Implementation code given by Tomasz Nurkiewicz from SO community only Overriding Service Method