文章目录
Spring MVC
Spring Web MVC是基于Servlet API构建的原始Web框架,从一开始就包含在Spring框架中。通过spring-webmvc引入。
核心类
DispatcherServlet
在web.xml中只用配置DispatcherServlet一个servlet,通过DispatcherServlet来分发请求。
类继承图
描述
Servlet:表示DispatcherServlet作为一个Servlet处理
GenericServlet:定义通用的、独立于协议的servlet
HttpServletBean:将Servlet配置信息作为 Bean的属性自动赋值给Servlet的属性
FrameworkServlet:提供了加载某个对应的web应用程序环境的功能,初始化WebApplicationContext
DispatcherServlet
public class DispatcherServlet extends FrameworkServlet {
// 处理器映射器
private List<HandlerMapping> handlerMappings;
// 处理器适配器
private List<HandlerAdapter> handlerAdapters;
// 视图解析器
private List<ViewResolver> viewResolvers;
// 构造函数
public DispatcherServlet(WebApplicationContext webApplicationContext) {
// 设置webApplicationContext
super(webApplicationContext);
setDispatchOptionsRequest(true);
}
}
HandlerMapping
处理器映射器,根据请求返回HandlerExecutionChain,默认实现为BeanNameUrlHandlerMapping(用bean名称作为映射)、RequestMappingHandlerMapping(@RequestMapping注解定义)
public interface HandlerMapping {
HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
}
// AbstractHandlerMethodMapping内部类存放映射关系
class MappingRegistry {
// RequestMappingInfo(patternsCondition(patterns:/login))
// MappingRegistration存放url和方法
private final Map<T, MappingRegistration<T>> registry = new HashMap<>();
// url和方法的映射 HandlerMethod->保有方法、bean、参数
private final Map<T, HandlerMethod> mappingLookup = new LinkedHashMap<>();
// 存放url:/login
private final MultiValueMap<String, T> urlLookup = new LinkedMultiValueMap<>();
// 存放方法:HandlerMethod
private final Map<String, List<HandlerMethod>> nameLookup = new ConcurrentHashMap<>();
}
HandlerInterceptor
拦截器,在获得处理器时同时处理拦截器,共同构建为HandlerExecutionChain
public interface HandlerInterceptor {
// 该方法将在请求处理handle之前进行调用
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return true;
}
// handle处理之后获得ModelAndView之后调用
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable ModelAndView modelAndView) throws Exception {
}
// 整个请求结束之后执行
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable Exception ex) throws Exception {
}
}
HandlerExecutionChain
执行处理链
public class HandlerExecutionChain {
// 通过HandlerMapping获得的处理器
private final Object handler;
// 拦截器
private HandlerInterceptor[] interceptors;
// toArray
private List<HandlerInterceptor> interceptorList;
private int interceptorIndex = -1;
}
HandlerAdapter
使用适配器模式生成处理器适配器,适配多个处理器,避免在DispatcherServlet中判断处理器类型,调用handle方法处理请求。
HttpRequestHandlerAdapter:无视图返回(null),适配静态资源处理
SimpleControllerHandlerAdapter:handler对象为Controller类型,调用handleRequest方法返回ModelAndView
RequestMappingHandlerAdapter:RequestMapping注解的处理器,通过HandlerMethod反射执行方法生成ModelAndView
public interface HandlerAdapter {
// 判断当前处理器适配器是否支持处理器实例
boolean supports(Object handler);
// 适配方法
ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;
}
ModelAndView
模型和视图,执行处理器后的返回结果
public class ModelAndView {
// 视图名或View类
private Object view;
// ModelMap extends LinkedHashMap<String, Object>
// Map存放数据
private ModelMap model;
// HTTP响应码
private HttpStatus status;
}
ViewResolver
视图解析器,把一个逻辑上的视图名称解析为一个真正的视图,默认实现InternalResourceViewResolver。
public interface ViewResolver {
View resolveViewName(String viewName, Locale locale) throws Exception;
}
View
最终的视图,url+contentType(text/html),通过请求转发器处理
public interface View {
// 渲染视图
void render(@Nullable Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
throws Exception;
}
初始化流程
- 监听启动,通过配置监听类ContextLoaderListener和上下文参数来初始化spring,首先通过反射生成的WebApplicationContext,然后调用refresh方法初始化后放入Servlet容器的context中。
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>
public void contextInitialized(ServletContextEvent event) {
// context中属性名:org.springframework.web.context.WebApplicationContext.ROOT
this.initWebApplicationContext(event.getServletContext());
}
- 分析DispatcherServlet设置初始参数(未设置使用默认/WEB-INF/dispatcher-servlet.xml,不存在则抛出异常)时初始化过程,首先调用HttpServletBean中的初始化方法,获取初始参数初始environment、contextConfigLocation上下文配置
public final void init() throws ServletException {
// 获得init初始参数
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
// 初始environment、contextConfigLocation上下文配置
if (!pvs.isEmpty()) {
try {
// BeanWrapper用来操作javaBean属性的工具,直接修改对象属性
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
}
// Let subclasses do whatever initialization they like.
initServletBean();
}
- 调用FrameworkServlet中initServletBean方法初始web上下文
protected final void initServletBean() throws ServletException {
long startTime = System.currentTimeMillis();
try {
// 根据配置文件初始web上下文
this.webApplicationContext = initWebApplicationContext();
// 空方法
initFrameworkServlet();
}
}
protected WebApplicationContext initWebApplicationContext() {
// 获得之前初始化的根容器(通过ContextLoaderListener初始化的)
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) {
// 设置父类容器
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
// 查看是否已在servlet上下文中注册了上下文实例
wac = findWebApplicationContext();
}
if (wac == null) {
// 创建容器
wac = createWebApplicationContext(rootContext);
}
// 当前子IOC容器仍未初始化完成则刷新
// ContextRefreshedEvent事件发布后会通过监听器调用onRefresh,refreshEventReceived=true
if (!this.refreshEventReceived) {
synchronized (this.onRefreshMonitor) {
onRefresh(wac);
}
}
if (this.publishContext) {
// 在上下文中注册改容器
// org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
}
return wac;
}
- 调用DispatcherServlet的onRefresh方法初始化DispatcherServlet
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
protected void initStrategies(ApplicationContext context) {
// 初始化MultipartResolver,主要处理文件上传服务。
initMultipartResolver(context);
// 处理应用的国际化,根据系统的运行语言来展示对应语言的页面
initLocaleResolver(context);
// 定义一个主题
initThemeResolver(context);
// 定义用户设置的请求映射关系,如果未定义则使用默认
initHandlerMappings(context);
// 根据Handler的类型,定义不同的处理器适配器
initHandlerAdapters(context);
// 定义异常处理器,处理Handler发送错误的情况
initHandlerExceptionResolvers(context);
// 在MAV没有视图名时调用RequestToViewNameTranslator从request中获得视图名
initRequestToViewNameTranslator(context);
// 定义视图解析器
initViewResolvers(context);
// 提供请求存储属性,供其他请求使用
initFlashMapManager(context);
}
- 对于HandlerMapping、HandlerAdapter、HandlerExceptionResolver和ViewResolver初始化过程相似,都是先检查参数detectAllXXX,如果为true,则默认从web上下文中搜索所有该类型的对象(配置了<mvc:annotation-driven/>会默认注册常用spring mvc组件);如果detectAllXXX为false,会在配置文件中查找用户定义的组件;如果未找到则使用DispatcherServlet.properties中配置的组件。
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
// detectAllHandlerMappings为true,从context中找出所有组件
if (this.detectAllHandlerMappings) {
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<>(matchingBeans.values());
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
}
else {
// 查找用户自定义
try {
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
}
// 未找到使用默认
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
}
}
执行过程
- 首先进入FrameworkServlet的service方法,一般GET和POST走的HttpServlet的service方法,然后再调用FrameworkServlet的doGet和doPost方法,本质上还是调用processRequest(request, response)来处理请求。
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
// 判断请求方式
if (httpMethod == HttpMethod.PATCH || httpMethod == null) {
processRequest(request, response);
}
else {
// 调用HttpServlet的service方法
super.service(request, response);
}
}
// FrameworkServlet的doPost方法
protected final void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
- 接下来分析FrameworkServlet的processRequest方法,初始化的全球化语言处理和请求属性,并将其绑定到当前线程,调用DispatcherServlet的doService方法。
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 开始时间
long startTime = System.currentTimeMillis();
Throwable failureCause = null;
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
// 当前请求系统语言 language:en region:us
LocaleContext localeContext = buildLocaleContext(request);
RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
// 异步管理
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
// 线程绑定全球化语言和请求属性
initContextHolders(request, localeContext, requestAttributes);
try {
// 核心,DispatcherServlet执行
doService(request, response);
}
·····
finally {
// 解除绑定
resetContextHolders(request, previousLocaleContext, previousAttributes);
if (requestAttributes != null) {
requestAttributes.requestCompleted();
}
logResult(request, response, failureCause, asyncManager);
// 发布request完成事件
publishRequestHandledEvent(request, response, startTime, failureCause);
}
}
- 进入DispatcherServlet类doService方法,继续为请求设置参数,首先判断是否为请求包含,是则保存属性快照;设置主题、ioc上下文等参数;设置flashMapManager。
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 如果是请求包含include则记录request属性
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));
}
}
}
// 将常用属性放入request中 locale、主题和ioc容器上下文
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) {
// 从session中获得请求转发前的属性
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()) {
// 如果是include请求将上面保存的属性快照重新放置到request中
if (attributesSnapshot != null) {
restoreAttributesAfterInclude(request, attributesSnapshot);
}
}
}
}
- DispatcherServlet的doDispatch方法,首先检查请求是否为文件上传,然后获得执行链,找不到则返回404,如果为get请求且内容无变化则直接返回304,调用拦截器的preHandle方法,使用适配器处理适配方法返回ModelAndView,如果MAV不为null且未设置视图名,则调用viewNameTranslator获得默认视图名,之后调用拦截器的postHandle方法,最后处理请求结果进行异常和视图渲染。
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);
// 通过请求获得处理执行链
// 调用afterPropertiesSet方法获得所有beanName遍历有对应注解的方法生成RequestMappingInfo,将类名+Method+Mapping存入registry、mappingLookup中
mappedHandler = getHandler(processedRequest);
// 未找到执行链处理404
if (mappedHandler == null) {
noHandlerFound(processedRequest, response);
return;
}
// 根据handler获得处理器适配器,遍历适配器调用其support方法判断
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// 如果是get请求且请求内容无变化,直接返回
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;
}
}
// 执行拦截器中preHandle方法,如果有一个拦截器返回false则调用拦截器的afterCompletion方法后return
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// 真实处理器处理请求的地方
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
// 异步直接返回
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
// 如果为设置view则使用默认
applyDefaultViewName(processedRequest, mv);
// 处理拦截器的PostHandle方法
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
// 处理请求结果,视图渲染、异常处理等
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Throwable err) {
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(processedRequest);
}
}
}
}
获得执行链过程
- 通过getHandler(processedRequest)方法,遍历当前的映射器取获得适配器,获得则退出不再遍历。
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
// 是否存在映射器
if (this.handlerMappings != null) {
// 遍历映射器
for (HandlerMapping mapping : this.handlerMappings) {
// 获得HandlerExecutionChain
HandlerExecutionChain handler = mapping.getHandler(request);
// 获得则返回不再执行下个映射器
if (handler != null) {
return handler;
}
}
}
return null;
}
- 执行AbstractHandlerMapping中的getHandler方法
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
// 子类实现获得处理器,根据request的uri来获得HandlerMethod(bean、参数、返回类型和方法)
Object handler = getHandlerInternal(request);
// 如果没有处理器则采用默认处理器
if (handler == null) {
handler = getDefaultHandler();
}
if (handler == null) {
return null;
}
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = obtainApplicationContext().getBean(handlerName);
}
// 构建执行链
HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
if (logger.isTraceEnabled()) {
logger.trace("Mapped to " + handler);
}
else if (logger.isDebugEnabled() && !request.getDispatcherType().equals(DispatcherType.ASYNC)) {
logger.debug("Mapped to " + executionChain.getHandler());
}
// 处理跨域请求
if (hasCorsConfigurationSource(handler) || CorsUtils.isPreFlightRequest(request)) {
CorsConfiguration config = (this.corsConfigurationSource != null ? this.corsConfigurationSource.getCorsConfiguration(request) : null);
CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
config = (config != null ? config.combine(handlerConfig) : handlerConfig);
executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
}
return executionChain;
}
- 执行链构建过程
protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) {
// 如果Handler不为HandlerExecutionChain 类型则new
HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ?
(HandlerExecutionChain) handler : new HandlerExecutionChain(handler));
// 获得请求的uri
String lookupPath = this.urlPathHelper.getLookupPathForRequest(request, LOOKUP_PATH);
// 遍历当前MappingHandler中的拦截器加入HandlerExecutionChain中
for (HandlerInterceptor interceptor : this.adaptedInterceptors) {
if (interceptor instanceof MappedInterceptor) {
MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
// 如果与uri匹配则加入interceptorList
if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) {
chain.addInterceptor(mappedInterceptor.getInterceptor());
}
}
else {
chain.addInterceptor(interceptor);
}
}
return chain;
}
处理请求结果过程
- processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);处理请求结果,这步之前获得了ModelAndView,这要进行异常处理和视图的渲染
private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
@Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,
@Nullable Exception exception) throws Exception {
boolean errorView = false;
// 处理异常
if (exception != null) {
if (exception instanceof ModelAndViewDefiningException) {
logger.debug("ModelAndViewDefiningException encountered", exception);
mv = ((ModelAndViewDefiningException) exception).getModelAndView();
}
else {
// 调用异常处理器处理
Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
mv = processHandlerException(request, response, handler, exception);
errorView = (mv != null);
}
}
// 视图不为空开始渲染视图
if (mv != null && !mv.wasCleared()) {
render(mv, request, response);
if (errorView) {
WebUtils.clearErrorRequestAttributes(request);
}
}
// 异步处理
if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
// Concurrent handling started during a forward
return;
}
// 调用拦截器中的AfterCompletion方法
if (mappedHandler != null) {
// Exception (if any) is already handled..
mappedHandler.triggerAfterCompletion(request, response, null);
}
}
- 视图渲染,通过视图名获得View,调用View的render方法绑定数据
protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
// 设置页面语言
Locale locale =
(this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale());
response.setLocale(locale);
View view;
String viewName = mv.getViewName();
if (viewName != null) {
// 根据视图名解析View,遍历视图解析器解析,
view = resolveViewName(viewName, mv.getModelInternal(), locale, request);
····视图空抛异常
}
else {
// 如果不存在视图名,直接取视图
view = mv.getView();
····视图空抛异常
}
try {
// 根据MAV中的值设置响应码
if (mv.getStatus() != null) {
response.setStatus(mv.getStatus().value());
}
// 根据modelMap中的数据渲染View
view.render(mv.getModelInternal(), request, response);
}
}
- 数据绑定,根据modelMap中的数据创建需要渲染的数据
public void render(@Nullable Map<String, ?> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
···记录日志
// 创建包含动态值、静态属性和pathVariables的组合
Map<String, Object> mergedModel = createMergedOutputModel(model, request, response);
// 提供子类实现,设置请求头
prepareResponse(request, response);
// 渲染合并视图和数据
renderMergedOutputModel(mergedModel, getRequestToExpose(request), response);
}
- 渲染合并视图和数据,以InternalResourceView为例,将model数据放入request,通过请求转发到目标资源。
protected void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// 将model数据绑定到request中
exposeModelAsRequestAttributes(model, request);
// 空方法
exposeHelpers(request);
// 确定请求分派的路径
String dispatcherPath = prepareForRendering(request, response);
// 获得请求转发器
RequestDispatcher rd = getRequestDispatcher(request, dispatcherPath);
···rd为null抛异常
// 如果为请求包含
if (useInclude(request, response)) {
response.setContentType(getContentType());
rd.include(request, response);
}
else {
// 请求转发到目标资源
rd.forward(request, response);
}
}