这就是service()
通常的实现方式(非常简化):
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);
}
}
正如你所看到的,它几乎没有委托给HTTP 方法doGet()
并doPost()
依赖于 HTTP 方法。所以从一只手上替换doGet()
和doPost()
用service()
就可以了。另一方面,您的 servlet 也将处理单独PUT
的、、和其他方法,DELETE
它将返回405 Method not allowed。HEAD
doGet()
doPost()
这就是为什么我实际上建议将代码分开doGet()
并doPost()
委托给您的代码,并让 servlet 处理其他方法。如果这是您的代码中重复出现的模式,请考虑以下帮助 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(.....);
}