SpringMVC执行过程
![20210705201138143](https://i-blog.csdnimg.cn/blog_migrate/a66471241eecd6bca61ca55a8bb339b0.jpeg)
- 起初用户发送请求
- 前端控制器
DispatchServlet
接收用户请求,并委托给 处理器映射HandlerMapping
HandlerMapping
根据请求路径寻找到相应的处理执行链HandlerExecutionChain
其中包含Handler
以及拦截器Interpetor
并返回给前端控制器DispatchServlet
将Handler
作为参数传递给合适的(根据Handler的实现方式-----基于(实现Controller, @Controller注解,实现HttpRequestHandler)HandlerAdapter
,适配器调用handler
方法处理核心业务逻辑并返回给前端控制器ModelAndView
DiapatchServlet
再次委托ViewResolver
将页面解析,并渲染而后返回视图解析器- 最终
DisparchServlet
相应了请求
AFQ:
为什么前端控制器不直接调用handler
,而是在中间加一个适配器?
这是因为处理者的实现有多种(或许你平常我们只用过@Controller,Spring后期确实推荐使用这种方法)
实现Controller, @Controller注解,实现HttpRequestHandler
每一种方式都对应了一个适配器,
HandlerAdapter
public interface HandlerAdapter {
boolean supports(Object handler);
ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;
long getLastModified(HttpServletRequest request, Object handler);
}
supports
,根据传入的handler判断是否,该适配器是否支持
handler
是处理具体的请求
SimpleControllerHandlerAdapter
能处理基于实现Controller接口的处理器
HttpRequestHandlerAdapter
能处理基于实现HttpRequestHandler接口的处理器
HttpRequestHandlerAdapter
能处理基于**@Controller**实现的处理器
如果没有适配器,直接调用,大概就是这样的
if(handler instanceof 实现Controller接口){
handler.handle(request,response)
}else if(handler instanceof 实现HttpRequestHandler接口){
handler.handle(request,response)
}else if(handler instanceof 基于@Controller){
handler.handle(request,response)
}....
多层的if else 并不优雅,并且,以后如果由其他实现方式的处理器,我们不得不,修改这段代码,添加新的if lese,
违背了开闭原则,所以,Spring 并不这么做,添加了适配器这一层,从若干个适配器中寻找到一个合适的处理器。
--------------------从容器中获取所有适配器----------------------------
private void initHandlerAdapters(ApplicationContext context) {
...
Map<String, HandlerAdapter> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);
...
}
-----------------------寻找合适的适配器----------------------------------
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
if (this.handlerAdapters != null) {
for (HandlerAdapter adapter : this.handlerAdapters) {
if (adapter.supports(handler)) {
return adapter;
}
}
}
...
}
这样做之后,就避免了大量的if else,让我们的代码更优雅
并且,如果将来新添加了其他处理器,我们只需要实现HandlerAdapter
,
为它创建一个适配器,需要修改任何原来的代码,符合开闭原则
ps:这里虽然用到了适配器,但我感觉但不是适配器模式
的思想(作为两个不兼容的接口之间的桥梁),而是Java多态
的应用
所有的过程基本上都围绕着
DispatchServlet
,而其中的核心逻辑又在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 {
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null) {
noHandlerFound(processedRequest, response);
return;
}
// Determine handler adapter for the current request.
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;
}
}
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
applyDefaultViewName(processedRequest, mv);
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);
}
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);
}
}
}
}