This is how service()
is typically implemented (very simplified):
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);
}
}
As you can see it barely delegates to doGet()
and doPost()
depending on HTTP method. So from one hand replacing doGet()
and doPost()
with service()
is fine. On the other hand your servlet will also handle PUT
, DELETE
, HEAD
and other methods while with separate doGet()
and doPost()
it will return 405 Method not allowed.
That's why I would actually advice separate doGet()
and doPost()
delegating to your code and let servlet handle other methods. If this is a recurring pattern in your code, consider the following helper servlet:
public class AbstractServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGetOrPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGetOrPost(request, response);
}
abstract protected void doGetOrPost(.....);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…