SpringMVC版本为5.1.14
Servlet生命周期
SpringMVC的请求流程都会经过DispatcherServlet
,它就是一个普通的Servlet,所有的请求都会被转发到这里。
Servlet 生命周期可被定义为从创建直到毁灭的整个过程。以下是 Servlet 遵循的过程:
- Servlet 通过调用 init () 方法进行初始化。
- Servlet 调用 service() 方法来处理客户端的请求。
- Servlet 通过调用 destroy() 方法终止(结束)。
Servlet接口如下
public interface Servlet {
void init(ServletConfig config) throws ServletException;
ServletConfig getServletConfig();
void service(ServletRequest req, ServletResponse res)throws ServletException, IOException;
String getServletInfo();
void destroy();
}
在编写Servlet的时候,都会继承HttpServlet
抽象类,HttpServlet
实现了Servlet
接口的service方法,根据请求方式的不同分发到不同的方法中,如下所示,如果请求方式为get,那么这个请求就会被HttpServlet的doGet方法处理。所以我们编写Servlet的时候,只需要重写HttpServlet
抽象类的doGet、doPost、doHead等方法就可以了。
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("<h1>MyServlet</h1>");
}
}
SpringMVC请求处理流程
①DispatcherServlet
是SpringMVC中的前端控制器,负责接收Request并将Request转发给对应的处理组件。
②HandlerMapping
是SpringMVC中完成URL到Controller映射的组件。DispatcherServlet
接收Request,然后从HandlerMapping
查找处理Request的Controller。
③Controller
处理Request,并返回ModelAndView
对象。ModelAndView
是封装结果视图的组件。
④、⑤、⑥、⑦是视图解析器解析ModelAndView
对象并返回对应的视图给客户端的过程。
DispatcherServlet
执行初始化方法 init()时会建立所有URL和Controller中方法的对应关系,保存到HandlerMapping
中,用户请求时根据请求的URL快速定位到Controller中的某个方法。
收集URL与Controller映射
RequestMappingHandlerMapping
RequestMappingHandlerMapping
实现了接口InitializingBean
,在bean加载完成后会自动调用afterPropertiesSet方法,在此方法中调用了initHandlerMethods()来实现初始化。- 遍历所有bean,如果bean实现带有注解@Controller或者@RequestMapping 则进一步调用detectHandlerMethods处理,处理逻辑大致就是根据@RequestMapping配置的信息,构建
RequestMappingInfo
,然后注册到MappingRegistry
中。
// RequestMappingHandlerMapping.java
@Override
public void afterPropertiesSet() {
this.config = new RequestMappingInfo.BuilderConfiguration();
this.config.setUrlPathHelper(getUrlPathHelper());
this.config.setPathMatcher(getPathMatcher());
this.config.setSuffixPatternMatch(this.useSuffixPatternMatch);
this.config.setTrailingSlashMatch(this.useTrailingSlashMatch);
this.config.setRegisteredSuffixPatternMatch(this.useRegisteredSuffixPatternMatch);
this.config.setContentNegotiationManager(getContentNegotiationManager());
// 调用父类 AbstractHandlerMethodMapping 的 afterPropertiesSet方法
super.afterPropertiesSet();
}
// AbstractHandlerMethodMapping.java
@Override
public void afterPropertiesSet() {
initHandlerMethods();
}
// AbstractHandlerMethodMapping.java
protected void initHandlerMethods() {
// getCandidateBeanNames() 获取所有bean的名字
for (String beanName : getCandidateBeanNames()) {
// 如果 bean 的名字前缀不为 SCOPED_TARGET_NAME_PREFIX(scopedTarget.)
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
processCandidateBean(beanName);
}
}
// 收集完所有的URL之后会调用这个方法,该方法没有什么实现
handlerMethodsInitialized(getHandlerMethods());
}
// AbstractHandlerMethodMapping.java
protected void processCandidateBean(String beanName) {
Class<?> beanType = null;
try {
// 获取 bean 的类型
beanType = obtainApplicationContext().getType(beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
if (logger.isTraceEnabled()) {
logger.trace("Could not resolve type for bean '" + beanName + "'", ex);
}
}
// isHandler方法用来判断这个类是否有 @Controller 或者是 @RequestMapping 注解
if (beanType != null && isHandler(beanType)) {
detectHandlerMethods(beanName);
}
}
// AbstractHandlerMethodMapping.java
protected void detectHandlerMethods(Object handler) {
// 获取 handler 的类型
// 如果 handler 为String类型的,说明 handler 为 bean 的名字,则去ioc容器获取 bean 的类型
Class<?> handlerType = (handler instanceof String ?
obtainApplicationContext().getType((String) handler) : handler.getClass());
if (handlerType != null) {
// 这里主要是为了返回用户定义的类
// 如果类被增强了,则需要返回原始类
Class<?> userType = ClassUtils.getUserClass(handlerType);
// methods 的 key 为 Method 类型, 保存了Controller中的方法,
// value 为 RequestMappingInfo 类型,封装了方法对应的URL信息
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
(MethodIntrospector.MetadataLookup<T>) method -> {
try {
// 这里是遍历 userType 中的所有方法
// 将@RequestMapping注解标注的方法信息,
// 封装成一个RequestMappingInfo
return getMappingForMethod(method, userType);
}
catch (Throwable ex) {
}
});
// 遍历methods
methods.forEach((method, mapping) -> {
Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
// 注册这个方法和url的映射关系
registerHandlerMethod(handler, invocableMethod, mapping);
});
}
}
// AbstractHandlerMethodMapping.java
protected void registerHandlerMethod(Object handler, Method method, T mapping) {
// 将信息保存到 MappingRegistry
// MappingRegistry 是 AbstractHandlerMethodMapping.java 中的内部类
this.mappingRegistry.register(mapping, handler, method);
}
// AbstractHandlerMethodMapping.java#MappingRegistry
public void register(T mapping, Object handler, Method method) {
// 加锁
this.readWriteLock.writeLock().lock();
try {
// 将 handler 和 method 封装成一个 HandlerMethod 对象
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
// 判断 mapping 是否是唯一的
assertUniqueMethodMapping(handlerMethod, mapping);
// 注册 mapping(RequestMappingInfo) 与 HandlerMethod 的映射关系
this.mappingLookup.put(mapping, handlerMethod);
// 获取这个 mapping 的所有URL地址,但是不包括@RequestMapping("/user/${id}")类型的
// RequestMapping的value是可以写多个URL地址的
List<String> directUrls = getDirectUrls(mapping);
for (String url : directUrls) {
// 注册 url 与 mapping(RequestMappingInfo)的映射关系
this.urlLookup.add(url, mapping);
}
String name = null;
if (getNamingStrategy() != null) {
// 返回类名的大写字母+#+方法名,例如UserController中的hello方法,
// 那么将会放回UH#hello
name = getNamingStrategy().getName(handlerMethod, mapping);
addMappingName(name, handlerMethod);
}
// 获取 cors 配置信息, 例如在方法上设置可跨域
CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping);
if (corsConfig != null) {
// 注册 handlerMethod 与 corsConfig 映射关系
this.corsLookup.put(handlerMethod, corsConfig);
}
// 注册 mapping 与 MappingRegistration的映射关系
// MappingRegistration 里面存储了 mapping(RequestMappingInfo)、handlerMethod、directUrls、name属性信息
this.registry.put(mapping, new MappingRegistration<>(mapping, handlerMethod, directUrls, name));
}
finally {
// 解锁
this.readWriteLock.writeLock().unlock();
}
}
此时,完成了URL地址与Controller中方法的映射关系。
DispatcherServlet
DispatcherServlet
继承FrameworkServlet
抽象类
FrameworkServlet
继承HttpServletBean
抽象类
HttpServletBean
继承HttpServlet
抽象类
DispatcherServlet
跟Servlet
一样也会经历init ()方法进行初始化,调用service() 方法来处理客户端的请求。
init ()
HttpServletBean
实现了init()方法
// HttpServletBean.java
public final void init() throws ServletException {
// Set bean properties from init parameters.
// 将init parameters封装到 PropertyValues pvs 中
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
// 将当前的这个 Servlet 对象,转化成一个 BeanWrapper 对象。
// 从而能够以 Spring 的方式来将 pvs 注入到该 BeanWrapper 对象。
// BeanWrapper 是 Spring 提供的一个用来操作 Java Bean 属性的工具,使用它可以直接修改一个对象的属性。
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
// 注册自定义属性编辑器,一旦碰到 Resource 类型的属性,
// 将会使用 ResourceEditor 进行解析
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
// 空实现,留给子类覆盖
initBeanWrapper(bw);
// 将 pvs 注入到该 BeanWrapper 对象中
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}
// Let subclasses do whatever initialization they like.
// 子类来实现,实现自定义的初始化逻辑
// FrameworkServlet实现了这个方法
initServletBean();
}
FrameworkServlet.initServletBean()
// FrameworkServlet.java
@Override
protected final void initServletBean() throws ServletException {
// ......省略不重要的代码
try {
// 初始化WEB容器
this.webApplicationContext = initWebApplicationContext();
// 这是一个空方法
initFrameworkServlet();
}
catch (ServletException | RuntimeException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
// ......省略不重要的代码
}
protected WebApplicationContext initWebApplicationContext() {
// 获取ROOT容器
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
if (cwac.getParent() == null) {
// 为WEB容器设置父容器
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
// 从ServletContext中获取WebApplicationContext
wac = findWebApplicationContext();
}
if (wac == null) {
// 创建 WebApplicationContext
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
// 这个方法由 DispatcherServlet 实现
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
// 将 WebApplicationContext 保存到 WebApplicationContext
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
DispatcherServlet.onRefresh(ApplicationContext context)
// DispatcherServlet.java
@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
// 初始化HandlerMapping
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
if (this.detectAllHandlerMappings) {
// 在容器中寻找类型为 HandlerMapping 的组件
// 如果使用了@EnableWebMvc注解,这里会返回三个, 分别为
// RequestMappingHandlerMapping
// BeanNameUrlHandlerMapping
// SimpleUrlHandlerMapping
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
// 将获取到的 HandlerMapping 保存起来
this.handlerMappings = new ArrayList<>(matchingBeans.values());
// 将获取到的 HandlerMappings 进行排序
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
}
else {
try {
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
}
}
// 如果前面找不到, 就注册默认的,确保至少存在一个HandlerMapping
// 默认返回两个
// RequestMappingHandlerMapping
// BeanNameUrlHandlerMapping
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
}
}
service
FrameworkServlet
实现了HttpServlet
的service(HttpServletRequest request, HttpServletResponse response)
方法
// FrameworkServlet
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取请求方式
HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
if (httpMethod == HttpMethod.PATCH || httpMethod == null) {
// 处理 PATCH 请求, 因为 HttpServlet 默认没提供
processRequest(request, response);
}
else {
// 调用父类 HttpServlet 的 service 方法,处理其它请求
super.service(request, response);
}
}
HttpServlet#service(HttpServletRequest req, HttpServletResponse resp)
代码如下
// HttpServlet.java
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) {
doGet(req, resp);
} else {
long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
if (ifModifiedSince < lastModified) {
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);
}
}
doGet、doPost、doPut 、doDelete等方法都被FrameworkServlet
重写了
// FrameworkServlet
@Override
protected final void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected final void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected final void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected final void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
这四个方法,都是直接调用 #processRequest(HttpServletRequest request, HttpServletResponse response)
方法,处理请求。代码如下:
// FrameworkServlet.java
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 记录当前时间
long startTime = System.currentTimeMillis();
Throwable failureCause = null;
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
LocaleContext localeContext = buildLocaleContext(request);
RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
// 将request、response封装成 ServletRequestAttributes 对象
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
// 将 requestAttributes 对象保存至 RequestContextHolder, 内部使用ThreadLocal保存
// 因此后续我们可以通过 RequestContextHolder 来获取HttpServletRequest、HttpServletResponse
initContextHolders(request, localeContext, requestAttributes);
try {
// 执行真正的逻辑
// 该抽象方法由 DispatcherServlet 实现
doService(request, response);
}
catch (ServletException | IOException ex) {
failureCause = ex;
throw ex;
}
catch (Throwable ex) {
failureCause = ex;
throw new NestedServletException("Request processing failed", ex);
}
finally {
resetContextHolders(request, previousLocaleContext, previousAttributes);
if (requestAttributes != null) {
requestAttributes.requestCompleted();
}
// 打印日志
logResult(request, response, failureCause, asyncManager);
// 发布 ServletRequestHandledEvent 事件
publishRequestHandledEvent(request, response, startTime, failureCause);
}
}
doService
DispatcherServlet#doService(HttpServletRequest request, HttpServletResponse response)
// DispatcherServlet.JAVA
@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 打印请求日志,并且日志级别为 DEBUG
logRequest(request);
// Keep a snapshot of the request attributes in case of an include,
// to be able to restore the original attributes after the include.
// 复制一份请求中的属性
Map<String, Object> attributesSnapshot = null;
if (WebUtils.isIncludeRequest(request)) {
attributesSnapshot = new HashMap<>();
Enumeration<?> attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {
attributesSnapshot.put(attrName, request.getAttribute(attrName));
}
}
}
// Make framework objects available to handlers and view objects.
// 设置Spring的一些常用属性到 request
request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());
if (this.flashMapManager != null) {
FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
if (inputFlashMap != null) {
request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
}
request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);
}
try {
// 执行请求的分发
doDispatch(request, response);
}
finally {
if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
// Restore the original attribute snapshot, in case of an include.
if (attributesSnapshot != null) {
restoreAttributesAfterInclude(request, attributesSnapshot);
}
}
}
}
doDispatch方法执行的就是这个流程
代码如下
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
ModelAndView mv = null;
Exception dispatchException = null;
try {
// 检查是否是上传请求。如果是,则封装成 MultipartHttpServletRequest 对象。
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
// Determine handler for the current request.
// 1. 获得请求对应的 HandlerExecutionChain 对象
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null) {
// 如果获取不到,则根据配置抛出异常或返回 404 错误
noHandlerFound(processedRequest, response);
return;
}
// Determine handler adapter for the current request.
// 2. 获得当前 handler 对应的 HandlerAdapter 对象
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// Process last-modified header, if supported by the handler.
String method = request.getMethod();
boolean isGet = "GET".equals(method);
if (isGet || "HEAD".equals(method)) {
long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
return;
}
}
// 3. 执行前置拦截器
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// Actually invoke the handler.
// 4. 执行 handler 方法,并返回视图
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
// 5. 设置默认的视图名
applyDefaultViewName(processedRequest, mv);
// 6. 执行后置拦截器
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
// As of 4.3, we're processing Errors thrown from handler methods as well,
// making them available for @ExceptionHandler methods and other scenarios.
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
// 7. 处理正常和异常的请求调用结果。
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
// 8. 异常时,触发拦截器的已完成处理
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Throwable err) {
// 8. 异常时,触发拦截器的已完成处理
triggerAfterCompletion(processedRequest, response, mappedHandler,
new NestedServletException("Handler processing failed", err));
}
finally {
if (asyncManager.isConcurrentHandlingStarted()) {
// Instead of postHandle and afterCompletion
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
}
else {
// Clean up any resources used by a multipart request.
if (multipartRequestParsed) {
// 如果是上传请求
// 则调用 cleanupMultipart(HttpServletRequest request) 方法,清理资源。
cleanupMultipart(processedRequest);
}
}
}
}
-
获得请求对应的
HandlerExecutionChain
对象。HandlerExecutionChain
对象包含了handler处理器和拦截器数组。这里返回的handler处理器类型为HandlerMethod
。主要分为三步:
第一:通过请求地址URL到
MappingRegistry
里面查找对应的HandlerMethod
第二:通过请求地址URL查找请求对应的拦截器(HandlerInterceptor)数组
第三:将
HandlerMethod
对象和拦截器(HandlerInterceptor)数组封装成HandlerExecutionChain
对象 -
获得当前 handler 对应的 HandlerAdapter 对象,用来执行handler方法,也就是执行我们的Controller方法。
-
执行前置拦截器。
-
执行 handler 方法,也就是执行Controller方法,并返回
ModelAndView
。 -
设置默认的视图名。
-
执行后置拦截器。
-
处理正常和异常的请求调用结果。
-
异常时,触发拦截器的已完成处理。