今天写Servlet类时,突然想到以前写的servlet里面有时候有service方法,有时候没有service,但是有doGet和doPost方法。
首先,得解释下servlet类中service()的地位。
最高层的接口Servlet(像HttpServlet等具体的Servlet都是直接或者间接实现了这个接口)里面就有这个方法,所以不管是怎样的servlet类,都有service方法。
HttpServlet类部分源码:
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;
try {
ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
} catch (IllegalArgumentException iae) {
// Invalid date header - proceed as if none was set
ifModifiedSince = -1;
}
if (ifModifiedSince < (lastModified / 1000 * 1000)) {
// 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);
}
}
当客户端请求一个servlet类的时候(不管是post还是get方法提交过来的连接)首先被调用的是service()。在service()中会根据Http请求的类型(Get,Post还是其他)来调用具体的doGet和doPost等方法;实际上时doGet和doPost方法最终来处理浏览器的请求。如果你重写了service方法,就不会再处理doPost或doGet了。
自己理解和百度的。如有错误,欢迎打脸。
版权声明:如果有不同看法,或者是文中写错的地方,麻烦大佬留言指正文章错误,谢谢!!!
原文出处:https://blog.csdn.net/blackplus28/article/details/80786751