Skip to content

Latest commit

History

History
737 lines (587 loc) · 23.9 KB

File metadata and controls

737 lines (587 loc) · 23.9 KB

SpringMVC

初始化阶段

Servlet

/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */packagejavax.servlet;
importjava.io.IOException;
publicinterfaceServlet {
publicvoidinit(ServletConfigconfig) throwsServletException;
publicServletConfiggetServletConfig();
publicvoidservice(ServletRequestreq, ServletResponseres)
throwsServletException, IOException;
publicStringgetServletInfo();
publicvoiddestroy();
}

GenericServlet

packagejavax.servlet;
importjava.io.IOException;
importjava.util.Enumeration;
publicabstractclassGenericServletimplementsServlet, ServletConfig,
java.io.Serializable {
privatestaticfinallongserialVersionUID = 1L;
privatetransientServletConfigconfig;
publicGenericServlet() {
// NOOP
}
@Overridepublicvoiddestroy() {
// NOOP by default
}
......
/** 初始化 */@Overridepublicvoidinit(ServletConfigconfig) throwsServletException {
this.config = config;
// 由子类实现this.init();
}
publicvoidinit() throwsServletException {
// NOOP by default
}
......
@Overridepublicabstractvoidservice(ServletRequestreq, ServletResponseres)
throwsServletException, IOException;
......
}

HttpServlet

packagejavax.servlet.http;
importjava.io.IOException;
importjava.io.OutputStreamWriter;
importjava.io.PrintWriter;
importjava.io.UnsupportedEncodingException;
importjava.lang.reflect.InvocationTargetException;
importjava.lang.reflect.Method;
importjava.text.MessageFormat;
importjava.util.Enumeration;
importjava.util.ResourceBundle;
importjavax.servlet.DispatcherType;
importjavax.servlet.GenericServlet;
importjavax.servlet.ServletException;
importjavax.servlet.ServletOutputStream;
importjavax.servlet.ServletRequest;
importjavax.servlet.ServletResponse;
publicabstractclassHttpServletextendsGenericServlet {
privatestaticfinallongserialVersionUID = 1L;
privatestaticfinalStringMETHOD_DELETE = "DELETE";
privatestaticfinalStringMETHOD_HEAD = "HEAD";
privatestaticfinalStringMETHOD_GET = "GET";
privatestaticfinalStringMETHOD_OPTIONS = "OPTIONS";
privatestaticfinalStringMETHOD_POST = "POST";
privatestaticfinalStringMETHOD_PUT = "PUT";
privatestaticfinalStringMETHOD_TRACE = "TRACE";
privatestaticfinalStringHEADER_IFMODSINCE = "If-Modified-Since";
privatestaticfinalStringHEADER_LASTMOD = "Last-Modified";
privatestaticfinalStringLSTRING_FILE =
"javax.servlet.http.LocalStrings";
privatestaticfinalResourceBundlelStrings =
ResourceBundle.getBundle(LSTRING_FILE);
/** * Does nothing, because this is an abstract class. */publicHttpServlet() {
// NOOP
}
protectedvoiddoGet(HttpServletRequestreq, HttpServletResponseresp)
throwsServletException, IOException
{
Stringmsg = lStrings.getString("http.method_get_not_supported");
sendMethodNotAllowed(req, resp, msg);
}
......
protectedvoiddoHead(HttpServletRequestreq, HttpServletResponseresp)
throwsServletException, IOException {
if (DispatcherType.INCLUDE.equals(req.getDispatcherType())) {
doGet(req, resp);
} else {
NoBodyResponseresponse = newNoBodyResponse(resp);
doGet(req, response);
response.setContentLength();
}
}
protectedvoiddoPost(HttpServletRequestreq, HttpServletResponseresp)
throwsServletException, IOException {
Stringmsg = lStrings.getString("http.method_post_not_supported");
sendMethodNotAllowed(req, resp, msg);
}
protectedvoiddoPut(HttpServletRequestreq, HttpServletResponseresp)
throwsServletException, IOException {
Stringmsg = lStrings.getString("http.method_put_not_supported");
sendMethodNotAllowed(req, resp, msg);
}
protectedvoiddoDelete(HttpServletRequestreq,
HttpServletResponseresp)
throwsServletException, IOException {
Stringmsg = lStrings.getString("http.method_delete_not_supported");
sendMethodNotAllowed(req, resp, msg);
}
......
protectedvoiddoOptions(HttpServletRequestreq,
HttpServletResponseresp)
throwsServletException, IOException {
Method[] methods = getAllDeclaredMethods(this.getClass());
booleanALLOW_GET = false;
booleanALLOW_HEAD = false;
booleanALLOW_POST = false;
booleanALLOW_PUT = false;
booleanALLOW_DELETE = false;
booleanALLOW_TRACE = true;
booleanALLOW_OPTIONS = true;
// Tomcat specific hack to see if TRACE is allowedClass<?> clazz = null;
try {
clazz = Class.forName("org.apache.catalina.connector.RequestFacade");
MethodgetAllowTrace = clazz.getMethod("getAllowTrace", (Class<?>[]) null);
ALLOW_TRACE = ((Boolean) getAllowTrace.invoke(req, (Object[]) null)).booleanValue();
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException |
IllegalAccessException | IllegalArgumentException | InvocationTargetExceptione) {
// Ignore. Not running on Tomcat. TRACE is always allowed.
}
// End of Tomcat specific hackfor (inti=0; i<methods.length; i++) {
Methodm = methods[i];
if (m.getName().equals("doGet")) {
ALLOW_GET = true;
ALLOW_HEAD = true;
}
if (m.getName().equals("doPost"))
ALLOW_POST = true;
if (m.getName().equals("doPut"))
ALLOW_PUT = true;
if (m.getName().equals("doDelete"))
ALLOW_DELETE = true;
}
Stringallow = null;
if (ALLOW_GET)
allow=METHOD_GET;
if (ALLOW_HEAD)
if (allow==null) allow=METHOD_HEAD;
elseallow += ", " + METHOD_HEAD;
if (ALLOW_POST)
if (allow==null) allow=METHOD_POST;
elseallow += ", " + METHOD_POST;
if (ALLOW_PUT)
if (allow==null) allow=METHOD_PUT;
elseallow += ", " + METHOD_PUT;
if (ALLOW_DELETE)
if (allow==null) allow=METHOD_DELETE;
elseallow += ", " + METHOD_DELETE;
if (ALLOW_TRACE)
if (allow==null) allow=METHOD_TRACE;
elseallow += ", " + METHOD_TRACE;
if (ALLOW_OPTIONS)
if (allow==null) allow=METHOD_OPTIONS;
elseallow += ", " + METHOD_OPTIONS;
resp.setHeader("Allow", allow);
}
protectedvoiddoTrace(HttpServletRequestreq, HttpServletResponseresp)
throwsServletException, IOException
{
intresponseLength;
StringCRLF = "\r\n";
StringBuilderbuffer = newStringBuilder("TRACE ").append(req.getRequestURI())
.append(" ").append(req.getProtocol());
Enumeration<String> reqHeaderEnum = req.getHeaderNames();
while( reqHeaderEnum.hasMoreElements() ) {
StringheaderName = reqHeaderEnum.nextElement();
buffer.append(CRLF).append(headerName).append(": ")
.append(req.getHeader(headerName));
}
buffer.append(CRLF);
responseLength = buffer.length();
resp.setContentType("message/http");
resp.setContentLength(responseLength);
ServletOutputStreamout = resp.getOutputStream();
out.print(buffer.toString());
out.close();
}
protectedvoidservice(HttpServletRequestreq, HttpServletResponseresp)
throwsServletException, IOException {
Stringmethod = req.getMethod();
if (method.equals(METHOD_GET)) {
longlastModified = getLastModified(req);
if (lastModified == -1) {
// servlet doesn't support if-modified-since, no reason// to go through further expensive logicdoGet(req, resp);
} else {
longifModifiedSince;
try {
ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
} catch (IllegalArgumentExceptioniae) {
// Invalid date header - proceed as if none was setifModifiedSince = -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 lessmaybeSetLastModified(resp, lastModified);
doGet(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
} elseif (method.equals(METHOD_HEAD)) {
longlastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp);
} elseif (method.equals(METHOD_POST)) {
doPost(req, resp);
} elseif (method.equals(METHOD_PUT)) {
doPut(req, resp);
} elseif (method.equals(METHOD_DELETE)) {
doDelete(req, resp);
} elseif (method.equals(METHOD_OPTIONS)) {
doOptions(req,resp);
} elseif (method.equals(METHOD_TRACE)) {
doTrace(req,resp);
} else {
//// Note that this means NO servlet supports whatever// method was requested, anywhere on this server.//StringerrMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = newObject[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}
}
@Overridepublicvoidservice(ServletRequestreq, ServletResponseres)
throwsServletException, IOException {
HttpServletRequestrequest;
HttpServletResponseresponse;
try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastExceptione) {
thrownewServletException(lStrings.getString("http.non_http"));
}
service(request, response);
}
}
// NoBodyResponse、NoBodyOutputStream
......

HttpServletBean

packageorg.springframework.web.servlet;
importjava.util.Enumeration;
importjava.util.HashSet;
importjava.util.Set;
importjavax.servlet.ServletConfig;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importorg.apache.commons.logging.Log;
importorg.apache.commons.logging.LogFactory;
importorg.springframework.beans.BeanWrapper;
importorg.springframework.beans.BeansException;
importorg.springframework.beans.MutablePropertyValues;
importorg.springframework.beans.PropertyAccessorFactory;
importorg.springframework.beans.PropertyValue;
importorg.springframework.beans.PropertyValues;
importorg.springframework.context.EnvironmentAware;
importorg.springframework.core.env.ConfigurableEnvironment;
importorg.springframework.core.env.Environment;
importorg.springframework.core.env.EnvironmentCapable;
importorg.springframework.core.io.Resource;
importorg.springframework.core.io.ResourceEditor;
importorg.springframework.core.io.ResourceLoader;
importorg.springframework.lang.Nullable;
importorg.springframework.util.Assert;
importorg.springframework.util.CollectionUtils;
importorg.springframework.util.StringUtils;
importorg.springframework.web.context.support.ServletContextResourceLoader;
importorg.springframework.web.context.support.StandardServletEnvironment;
@SuppressWarnings("serial")
publicabstractclassHttpServletBeanextendsHttpServletimplementsEnvironmentCapable, EnvironmentAware {
/** Logger available to subclasses. */protectedfinalLoglogger = LogFactory.getLog(getClass());
@NullableprivateConfigurableEnvironmentenvironment;
privatefinalSet<String> requiredProperties = newHashSet<>(4);
protectedfinalvoidaddRequiredProperty(Stringproperty) {
this.requiredProperties.add(property);
}
......
/** tomcat启动,就会执行该方法,初始化DispatcherServlet */@Overridepublicfinalvoidinit() throwsServletException {
// Set bean properties from init parameters.PropertyValuespvs = newServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
BeanWrapperbw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoaderresourceLoader = newServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, newResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansExceptionex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throwex;
}
}
// 初始化 web 环境,执行 FrameworkServlet#initServletBean() 方法initServletBean();
}
......
}

FrameworkServlet

publicabstractclassFrameworkServletextendsHttpServletBeanimplementsApplicationContextAware {
@OverrideprotectedfinalvoidinitServletBean() throwsServletException {
getServletContext().log("Initializing Spring " + getClass().getSimpleName() + " '" + getServletName() + "'");
if (logger.isInfoEnabled()) {
logger.info("Initializing Servlet '" + getServletName() + "'");
}
longstartTime = System.currentTimeMillis();
try {
// 初始化 web 环境this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
catch (ServletException | RuntimeExceptionex) {
logger.error("Context initialization failed", ex);
throwex;
}
if (logger.isDebugEnabled()) {
Stringvalue = this.enableLoggingRequestDetails ?
"shown which may lead to unsafe logging of potentially sensitive data" :
"masked to prevent unsafe logging of potentially sensitive data";
logger.debug("enableLoggingRequestDetails='" + this.enableLoggingRequestDetails +
"': request parameters and headers will be " + value);
}
if (logger.isInfoEnabled()) {
logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms");
}
}
protectedWebApplicationContextinitWebApplicationContext() {
WebApplicationContextrootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContextwac = null;
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use itwac = this.webApplicationContext;
if (wacinstanceofConfigurableWebApplicationContext) {
ConfigurableWebApplicationContextcwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as// setting the parent context, setting the application context id, etcif (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set// the root application context (if any; may be null) as the parentcwac.setParent(rootContext);
}
/* 配置和刷新Spring容器 初始化Spring IOC环境,这个方法最终会调用 refresh() 方法 */configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
// No context instance was injected at construction time -> see if one// has been registered in the servlet context. If one exists, it is assumed// that the parent context (if any) has already been set and that the// user has performed any initialization such as setting the context idwac = findWebApplicationContext();
}
if (wac == null) {
// No context instance is defined for this servlet -> create a local onewac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh// support or the context injected at construction time had already been// refreshed -> trigger initial onRefresh manually here.synchronized (this.onRefreshMonitor) {
// 初始化DispatcherServlet的配置,由子类实现onRefresh(wac);
}
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.StringattrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
}
returnwac;
}
protectedvoidconfigureAndRefreshWebApplicationContext(ConfigurableWebApplicationContextwac) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value// -> assign a more useful id based on available informationif (this.contextId != null) {
wac.setId(this.contextId);
}
else {
// Generate default id...wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
}
}
wac.setServletContext(getServletContext());
wac.setServletConfig(getServletConfig());
wac.setNamespace(getNamespace());
wac.addApplicationListener(newSourceFilteringListener(wac, newContextRefreshListener()));
// The wac environment's #initPropertySources will be called in any case when the context// is refreshed; do it eagerly here to ensure servlet property sources are in place for// use in any post-processing or initialization that occurs below prior to #refreshConfigurableEnvironmentenv = wac.getEnvironment();
if (envinstanceofConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
}
postProcessWebApplicationContext(wac);
applyInitializers(wac);
wac.refresh();
}
}

DispatcherServlet

publicclassDispatcherServletextendsFrameworkServlet {
@OverrideprotectedvoidonRefresh(ApplicationContextcontext) {
initStrategies(context);
}
protectedvoidinitStrategies(ApplicationContextcontext) {
initMultipartResolver(context);// 文件上传解析器initLocaleResolver(context);// 国际化解析器initThemeResolver(context);// 网页主题解析器initHandlerMappings(context);// 初始化 HandlerMappinginitHandlerAdapters(context);// 初始化 HandlerAdapterinitHandlerExceptionResolvers(context);// 处理器异常解析器initRequestToViewNameTranslator(context);
initViewResolvers(context);// 视图解析器initFlashMapManager(context);// 重定向数据管理器
}
}

请求处理阶段

用户的一个请求过来,会由Servlet接收到,然后一步一步调用到DispatcherServlet的doService方法。

# 请求调用链
Servlet#service
-> GenericServlet#service
-> HttpServlet#service(ServletRequest, ServletResponse)
-> HttpServletBean
-> FrameworkServlet#service
-> FrameworkServlet#processRequest
-> DispatcherServlet#doService
  1. doDispatch
publicclassDispatcherServletextendsFrameworkServlet {
protectedvoiddoDispatch(HttpServletRequestrequest, HttpServletResponseresponse) throwsException {
HttpServletRequestprocessedRequest = request;
HandlerExecutionChainmappedHandler = null;
booleanmultipartRequestParsed = false;
WebAsyncManagerasyncManager = WebAsyncUtils.getAsyncManager(request);
try {
ModelAndViewmv = null;
ExceptiondispatchException = null;
try {
// 检查请求中是否有文件上传操作processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
// mappedHandler调用链,该对象封装了handler和interceptorsmappedHandler = getHandler(processedRequest);
// mappedHandler没找到,响应404if (mappedHandler == null) {
noHandlerFound(processedRequest, response);
return;
}
// 获取处理器适配器// 如果是一个bean,mappedHandler.getHandler()返回的是一个对象// 如果是一个method,mappedHandler.getHandler()返回的是一个方法HandlerAdapterha = getHandlerAdapter(mappedHandler.getHandler());
// 处理请求头Stringmethod = request.getMethod();
booleanisGet = "GET".equals(method);
if (isGet || "HEAD".equals(method)) {
longlastModified = ha.getLastModified(request, mappedHandler.getHandler());
if (newServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
return;
}
}
// 前置拦截器if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// 通过处理器适配器,处理请求,反射调用mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
// 视图解析器处理applyDefaultViewName(processedRequest, mv);
// 后置拦截器mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exceptionex) {
dispatchException = ex;
}
catch (Throwableerr) {
// As of 4.3, we're processing Errors thrown from handler methods as well,// making them available for @ExceptionHandler methods and other scenarios.dispatchException = newNestedServletException("Handler dispatch failed", err);
}
// 异常处理,渲染页面,执行拦截器的afterCompletion()方法processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exceptionex) {
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Throwableerr) {
triggerAfterCompletion(processedRequest, response, mappedHandler,
newNestedServletException("Handler processing failed", err));
}
finally {
if (asyncManager.isConcurrentHandlingStarted()) {
// Instead of postHandle and afterCompletionif (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
}
else {
// Clean up any resources used by a multipart request.if (multipartRequestParsed) {
cleanupMultipart(processedRequest);
}
}
}
}
}