1. 下面是一个简单的时序图:
![web容器调用Filter和Servlet顺序学习 web容器调用Filter和Servlet顺序学习](https://i-blog.csdnimg.cn/blog_migrate/47378af2c62c540074afd50c5a1617bc.jpeg)
2. 对上面时序图中用到的主要类进行分析
1) ApplicationFilterChain类,有两个主要函数,下面是省略过会的代码
public voiddoFilter(request, response) {//暴露在外面的调用接口
if( Globals.IS_SECURITY_ENABLED ) {
finalServletRequest req = request;
finalServletResponse res = response;
internalDoFilter(req,res);
return null;
} else {
internalDoFilter(request,response);
}
}
private voidinternalDoFilter(request, response) {
if (pos < n) {//判断是否还有filter需要执行
ApplicationFilterConfig filterConfig = filters[pos++];
Filter filter = null;
filter = filterConfig.getFilter();
filter.doFilter(request, response, this);
return ;
}
{//filter执行完后,执行servlet
if ((request instanceofHttpServletRequest) &&
(response instanceof HttpServletResponse)) {
servlet.service((HttpServletRequest) request,
(HttpServletResponse) response);
}
}
void addFilter(ApplicationFilterConfig filterConfig) {
if (n == filters.length) {
ApplicationFilterConfig[] newFilters =
new ApplicationFilterConfig[n + INCREMENT];
System.arraycopy(filters, 0, newFilters, 0, n);
filters = newFilters;
}
filters[n++] = filterConfig;
}
2) Servlet类的主要方法,以HttpServlet类为例,其主要方法是service(Request,Response)
public voidservice(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) {
throw new ServletException("non-HTTP request or response");
}
service(request, response);//内部的方法
}
protected voidservice(HttpServletRequest , HttpServletResponse)
throws ServletException, IOException {
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
long lastModified = getLastModified(req);
if (lastModified == -1) {
doGet(req, resp); //常用的方法
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
} catch (IllegalArgumentException iae) {
ifModifiedSince = -1;
}
if (ifModifiedSince < (lastModified / 1000 * 1000)) {
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 {
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);