下面的图片描述了servlet架构。
它表示 HttpServlet 类不需要实现service()方法,因为它由 GenericServlet 类处理。 HttpServlet 类只能实现doGet()和doPost()方法。
疑
在此图层次结构中,doGet()和doPost()的签名在哪里,即doGet()/ doPost()的实现如何在GenericServlet类中触发对service()的调用,因为甚至是抽象签名在GenericServlet类中没有doGet()和doPost()。
问题
我相信在超类GenericServlet的service()方法中存在对这些方法的嵌套调用。这是正确的感知还是以其他方式起作用?
答案 0 :(得分:0)
您的怀疑几乎是正确的,对doGet()
,doPost()
和其他do方法的调用都在HttpServlet
类中,该类扩展为GenericServlet
。这取自Servlet API jar的3.1版(参见the source code starting at line 677):
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
long lastModified = getLastModified(req);
if (lastModified == -1) {
// servlet doesn't support if-modified-since, no reason
// to go through further expensive logic
doGet(req, resp);
} else {
long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
if (ifModifiedSince < lastModified) {
// If the servlet mod time is later, call doGet()
// Round down to the nearest second for a proper compare
// A ifModifiedSince of -1 will always be less
maybeSetLastModified(resp, lastModified);
doGet(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
} else if (method.equals(METHOD_HEAD)) {
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
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 {
//
// Note that this means NO servlet supports whatever
// method was requested, anywhere on this server.
//
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}
}