SpringMVC 处理器执行链 (HandlerMapping)的执行过程
第一步:在web.xml中找到DispatcherServlet,然后ctrl+鼠标左键进入这个类中
第二步:ctrl+f找一个叫doDispatch的方法
//入参进来一个request 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 err = null; 异常 Exception dispatchException = null; try { //指的是 DispatcherServlet 的实例 看看请求是不是多部分请求 <form enctype="multipart/form-data"> 表单有文件域 上传文件了 processedRequest = this.checkMultipart(request); multipartRequestParsed = processedRequest != request;
mappedHandler = this.getHandler(processedRequest);
第三步:ctrl+鼠标左键进入getHandler方法中
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { handlerMappings单列集合 。Set List Iterator var2 = this.handlerMappings.iterator(); HandlerExecutionChain handler; if(!var2.hasNext()) return null; 每next()拿到一个HandlerMapping实例 HandlerMapping hm = (HandlerMapping)var2.next(); handler = hm.getHandler(request); return handler; }
第四步:接着ctrl+鼠标左键找getHandler方法,我们找到的是一个接口,然后ctrl+h找接口的实现类 AbstractHandlerMapping(抽象类)
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { Object handler = this.getHandlerInternal(request); if(handler == null) { handler = this.getDefaultHandler(); } if(handler == null) { return null; } else { if(handler instanceof String) { String handlerName = (String)handler; // /hello handler = this.getApplicationContext().getBean(handlerName); } return this.getHandlerExecutionChain(handler, request); } }
第五步:找getHandlerExecutionChain方法
protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) { HandlerExecutionChain chain = handler instanceof HandlerExecutionChain?(HandlerExecutionChain)handler:new HandlerExecutionChain(handler); String lookupPath = this.urlPathHelper.getLookupPathForRequest(request); Iterator var5 = this.adaptedInterceptors.iterator(); while(var5.hasNext()) { HandlerInterceptor interceptor = (HandlerInterceptor)var5.next(); if(interceptor instanceof MappedInterceptor) { MappedInterceptor mappedInterceptor = (MappedInterceptor)interceptor; if(mappedInterceptor.matches(lookupPath, this.pathMatcher)) { chain.addInterceptor(mappedInterceptor.getInterceptor()); } } else { chain.addInterceptor(interceptor); } } return chain; }