SpringMVC是怎么处理请求的?
SpringMVC实现了传统的javax.servlet,将一系列请求过程中非业务的内容进行封装,使我们可以专注于业务的开发,那么它是怎么进行封装的?
DispatcherServlet
这是SpringMVC实现的的Servlet,也是它处理请求最核心的类,整个请求的处理流程都可以通过分析这个类了解清楚。
这是DispatcherServlet的继承关系图:
![](https://img.haomeiwen.com/i3797511/cc68c3b49b78c918.png)
HttpServletBean覆写了init方法,对初始化过程做了一些处理
public final void init() throws ServletException {
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}
initServletBean();
}
其中ServletConfigPropertyValues会利用ServletConfig对象从web.xml中突出配置参数,并设置到ServletConfigPropertyValues中。
initServletBean()在子类FrameworkServlet中被实现:
protected final void initServletBean() throws ServletException {
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
它最重要的是初始化了webApplicationContext,这是Spring容器上下文,通过FrameworkServlet后,Servlet和Spring容器就关联起来了,initFrameworkServlet()供子类复写做一些需要的处理。
请求处理过程
DispatcherServlet通过onDispatch方法来处理每个请求,核心流程通过以下代码来体现:
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
ModelAndView mv = null;
Exception dispatchException = null;
try {
processedRequest = checkMultipart(request);
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest); // 步骤一
// Determine handler adapter for the current request.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); //步骤二
if (!mappedHandler.applyPreHandle(processedRequest, response)) { //步骤三
return;
}
// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); //步骤四
mappedHandler.applyPostHandle(processedRequest, response, mv); //步骤五
}
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException); //步骤六
}
}
- 步骤一:通过this.handlerMappings找到HandlerExecutionChain,而在HandlerExecutionChain内部包装了拦截器HandlerInterceptor
- 步骤二:遍历this.handlerAdapters集合,通过HandlerExecutionChain中的Handler来找到支持此Handler的HandlerAdapter
- 步骤三:调用HandlerInterceptor的preHandle方法做前置处理
- 步骤四:通过HandlerAdapter的handle方法得到ModeAndView
- 步骤五:调用HandlerInterceptor的postHandle方法做后置处理
- 步骤六:调用processDispatchResult对ModeAndView做处理,同时,在上面步骤中发生的异常也一并在processDispatchResult中处理,最终异常会被HandlerExceptionResolver处理掉;接着processDispatchResult继续处理ModeAndView,调用ViewResolver的resolveViewName得到View对象,接着调用View的render方法得到最终的结果,在render方法中传入了Response作为参数,便于接收最终的结果
以上六个步骤就是SpringMVC处理请求的核心流程,在每个流程中还有很多细节。
![](https://img.haomeiwen.com/i3797511/03ab4878ff875acf.png)
请求处理方法的查找
在AbstractHandlerMethodMapping的initHandlerMethods中:
protected void initHandlerMethods() {
String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
getApplicationContext().getBeanNamesForType(Object.class));
for (String beanName : beanNames) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
Class<?> beanType = null;
try {
beanType = getApplicationContext().getType(beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
}
}
if (beanType != null && isHandler(beanType)) {
detectHandlerMethods(beanName);
}
}
}
handlerMethodsInitialized(getHandlerMethods());
}
protected boolean isHandler(Class<?> beanType) {
return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
}
先找到Spring容器初始化时的所有bean的名字,然后遍历这些名字,通过isHandler来判断这些bean是否@Controller和@RequestMapping修饰,有的话执行detectHandlerMethods方法。
protected void detectHandlerMethods(final Object handler) {
Class<?> handlerType = (handler instanceof String ?
getApplicationContext().getType((String) handler) : handler.getClass());
final Class<?> userType = ClassUtils.getUserClass(handlerType);
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
new MethodIntrospector.MetadataLookup<T>() {
@Override
public T inspect(Method method) {
try {
return getMappingForMethod(method, userType);
}
catch (Throwable ex) {
throw new IllegalStateException("Invalid mapping on handler class [" +
userType.getName() + "]: " + method, ex);
}
}
});
if (logger.isDebugEnabled()) {
logger.debug(methods.size() + " request handler methods found on " + userType + ": " + methods);
}
for (Map.Entry<Method, T> entry : methods.entrySet()) {
Method invocableMethod = AopUtils.selectInvocableMethod(entry.getKey(), userType);
T mapping = entry.getValue();
registerHandlerMethod(handler, invocableMethod, mapping);
}
}
在detectHandlerMethods方法中,核心的是getMappingForMethod和registerHandlerMethod这两个方法,getMappingForMethod在子类RequestMappingHandlerMapping中实现:
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
RequestMappingInfo info = createRequestMappingInfo(method);
if (info != null) {
RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
if (typeInfo != null) {
info = typeInfo.combine(info);
}
}
return info;
}
它先查找方法的@RequestMapping注解,然后再查找类的@RequestMapping注解,如果都存在的话执行合并操作,最终会合并成一个RequestMappingInfo。
一些核心类
HandlerMethod
一个封装了Method和Parameter的辅助类,在HandlerMapping中构造,在HandlerAdapter中消费。
// class AbstractHandlerMethodMapping
private static final HandlerMethod PREFLIGHT_AMBIGUOUS_MATCH =
new HandlerMethod(new EmptyHandler(), ClassUtils.getMethod(EmptyHandler.class, "handle"));
// class AbstractHandlerMethodAdapter
public final boolean supports(Object handler) {
return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler));
}
public final long getLastModified(HttpServletRequest request, Object handler) {
return getLastModifiedInternal(request, (HandlerMethod) handler);
}
RequestMappingHandlerAdapter
HandlerAdapter的核心继承类,内部的HandlerMethodArgumentResolver和HandlerMethodReturnValueHandler分别负责对方法参数的解析和方法返回值的处理。比如HandlerMethodArgumentResolver的子类RequestParamMethodArgumentResolver处理@RequestParam参数的解析;HandlerMethodReturnValueHandler的子类ModelAndViewMethodReturnValueHandler处理ModeAndView的返回;在它们两共同的实现类RequestResponseBodyMethodProcessor中,处理@RequestBody注解的解析和@ResponseBody参数的返回等。
网友评论