springMVC如何找到Controller并接收参数

直接从DispatcherServlet的doDispatch说起,之前的内容请参照前一篇文章

  1. doDispatch方法下的代码
    HandlerExecutionChain mappedHandler = null;
    //通过getHandler获取到对应HandlerExecutionChain
    mappedHandler = this.getHandler(processedRequest);
@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;
}
  1. handlerMappings来源,在第一次进入是调用
 protected void onRefresh(ApplicationContext context) {
        this.initStrategies(context);
    }
 protected void initStrategies(ApplicationContext context) {
        this.initMultipartResolver(context);
        this.initLocaleResolver(context);
        this.initThemeResolver(context);
        this.initHandlerMappings(context);
        this.initHandlerAdapters(context);
        this.initHandlerExceptionResolvers(context);
        this.initRequestToViewNameTranslator(context);
        this.initViewResolvers(context);
        this.initFlashMapManager(context);
    }
	
private void initHandlerMappings(ApplicationContext context) {
	this.handlerMappings = null;
	if (this.detectAllHandlerMappings) {
		Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
		if (!matchingBeans.isEmpty()) {
			//从context取出,并赋值给handlerMappings
			this.handlerMappings = new ArrayList(matchingBeans.values());
			AnnotationAwareOrderComparator.sort(this.handlerMappings);
		}
	}
	...
}
  1. 如何将请求与controller对应,doDispatch方法中有以下代码,该代码吧请求的request与handler传入并返回了视图
 mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
  1. 所以所有的关联均在(AbstractHandlerMethodAdapter类)ha.handle方法内
	@Override
   public final ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
   		throws Exception {
   	return handleInternal(request, response, (HandlerMethod) handler);
   }
	protected abstract ModelAndView handleInternal(HttpServletRequest request,
   		HttpServletResponse response, HandlerMethod handlerMethod) throws Exception;
  1. 之后找到了抽象方法的实现RequestMappingHandlerAdapter的handleInternal方法
protected ModelAndView handleInternal(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
       this.checkRequest(request);
       ModelAndView mav;
       if (this.synchronizeOnSession) {
           HttpSession session = request.getSession(false);
           if (session != null) {
               Object mutex = WebUtils.getSessionMutex(session);
               synchronized(mutex) {
                   mav = this.invokeHandlerMethod(request, response, handlerMethod);
               }
           } else {
               mav = this.invokeHandlerMethod(request, response, handlerMethod);
           }
       } else {
           mav = this.invokeHandlerMethod(request, response, handlerMethod);
       }
   	...
   }
  1. invokeHandlerMethod详细解析此方法
@Nullable
   protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
       ServletWebRequest webRequest = new ServletWebRequest(request, response);

       Object result;
       try {
           WebDataBinderFactory binderFactory = this.getDataBinderFactory(handlerMethod);
           ModelFactory modelFactory = this.getModelFactory(handlerMethod, binderFactory);
           ServletInvocableHandlerMethod invocableMethod = this.createInvocableHandlerMethod(handlerMethod);
           if (this.argumentResolvers != null) {
               invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
           }

           if (this.returnValueHandlers != null) {
               invocableMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
           }

           invocableMethod.setDataBinderFactory(binderFactory);
           invocableMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);
           ModelAndViewContainer mavContainer = new ModelAndViewContainer();
           mavContainer.addAllAttributes(RequestContextUtils.getInputFlashMap(request));
           modelFactory.initModel(webRequest, mavContainer, invocableMethod);//参数获取
           mavContainer.setIgnoreDefaultModelOnRedirect(this.ignoreDefaultModelOnRedirect);
           AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response);
           asyncWebRequest.setTimeout(this.asyncRequestTimeout);
           WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
           asyncManager.setTaskExecutor(this.taskExecutor);
           asyncManager.setAsyncWebRequest(asyncWebRequest);
           asyncManager.registerCallableInterceptors(this.callableInterceptors);
           asyncManager.registerDeferredResultInterceptors(this.deferredResultInterceptors);
           if (asyncManager.hasConcurrentResult()) {
               result = asyncManager.getConcurrentResult();
               mavContainer = (ModelAndViewContainer)asyncManager.getConcurrentResultContext()[0];
               asyncManager.clearConcurrentResult();
               LogFormatUtils.traceDebug(this.logger, (traceOn) -> {
                   String formatted = LogFormatUtils.formatValue(result, !traceOn);
                   return "Resume with async result [" + formatted + "]";
               });
               invocableMethod = invocableMethod.wrapConcurrentResult(result);
           }

           invocableMethod.invokeAndHandle(webRequest, mavContainer, new Object[0]);
           if (!asyncManager.isConcurrentHandlingStarted()) {
               ModelAndView var15 = this.getModelAndView(mavContainer, modelFactory, webRequest);
               return var15;
           }

           result = null;
       } finally {
           webRequest.requestCompleted();
       }

       return (ModelAndView)result;
   }
  1. modelFactory.initModel(webRequest, mavContainer, invocableMethod);参数是通过此方法加入到mavContainer中,仔细看看不就是request的参数获取嘛
 public void initModel(NativeWebRequest request, ModelAndViewContainer container, HandlerMethod handlerMethod) throws Exception {
        Map<String, ?> sessionAttributes = this.sessionAttributesHandler.retrieveAttributes(request);
        container.mergeAttributes(sessionAttributes);
        this.invokeModelAttributeMethods(request, container);
        Iterator var5 = this.findSessionAttributeArguments(handlerMethod).iterator();
        while(var5.hasNext()) {
            String name = (String)var5.next();
            if (!container.containsAttribute(name)) {
                Object value = this.sessionAttributesHandler.retrieveAttribute(request, name);
                if (value == null) {
                    throw new HttpSessionRequiredException("Expected session attribute '" + name + "'", name);
                }

                container.addAttribute(name, value);
            }
        }

    }

猜你喜欢

转载自blog.csdn.net/i6725545/article/details/87859250
今日推荐