SpringMVC请求处理流程
- 发起请求到前端控制器(DispatcherServlet)
- 前端控制器请求HandlerMapping查找Handler(可以根据xml配置,注解进行查找)
对应Spring源码
//在类DispatcherServlet里面
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
try {
ModelAndView mv = null;
Exception dispatchException = null;
try {
processedRequest = this.checkMultipart(request);
multipartRequestParsed = processedRequest != request;
mappedHandler = this.getHandler(processedRequest);
//getHandler方法内部会遍历配置的HandlerMapping实例来找到请求相匹配的Handler
//...其余代码省略
}
- 处理器映射器HandlerMapping向前端控制器返回Handler,HandlerMapping会把请求映射为HandlerExecutionChain对象(包含一个Handler处理器(页面控制器)对象,多个HandlerInterceptor拦截器对象),通过这种策略模式,很容易添加新的映射策略
对应Spring源码
@Nullable
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
if (this.handlerMappings != null) {
Iterator var2 = this.handlerMappings.iterator();
while(var2.hasNext()) {
HandlerMapping mapping = (HandlerMapping)var2.next();
HandlerExecutionChain handler = mapping.getHandler(request);
if (handler != null) {
return handler;
}
}
}
return null;
}
- 前端控制器调用处理器去执行Handler
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
//代码省略......
mappedHandler = this.getHandler(processedRequest);
if (mappedHandler == null) {
this.noHandlerFound(processedRequest, response);
return;
}
HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
//代码省略
- 处理器适配器HandlerAdapter将会根据适配去执行Handler
- Handler执行完成给适配器返回ModelAndView
- 处理器适配器向前端控制器返回ModelAndView(ModelAndView是SpringMVC框架的一个底层对象,包括Model和view)
try {
try {
ModelAndView mv = null;
//代码省略....
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
//代码省略....
- 前端控制器请求视图解析器去进行视图解析(根据逻辑视图名解析成真正的视图(jsp)),通过这种策略很容易更换其他视图技术,只需要更换视图解析器即可
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
//代码省略....
this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);
//代码省略///
- 视图解析器向前端控制器返回view
- 前端控制器进行视图渲染(视图渲染将模型数据(在ModelAndView对象中)填充到request域)
- 前端控制器向用户响应结果