RequestMappingHandlerAdapter类详解 - HandlerAdapter系列三

RequestMappingHandlerAdapter继承了AbstractHandlerMethodAdapter类,真正意义上实现了HandlerAdapter 接口定义的功能。

supportsInternal() 默认返回 true

protected boolean supportsInternal(HandlerMethod handlerMethod) {
    return true;
}

说明只要处理器是 HandlerMethod 类即可.

handleInternal() 负责调用 HandlerMethod(处理器),并返回 ModelAndView

protected ModelAndView handleInternal(HttpServletRequest request, HttpServletResponse response, 
    HandlerMethod handlerMethod) throws Exception {
    // 1.校验请求
    // 检查是否支持当前 rqeuest 的 method 和 session
    checkRequest(request);

    // 2.判断控制器是否存在 @SessionAttributes 注解
    if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {
        // 2.1设置缓存
        applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);
    } else {
        // 2.2准备响应
        prepareResponse(response);
    }

    // 默认为 false,为 true 表示在同步块中执行 invokeHandlerMethod
    if (this.synchronizeOnSession) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object mutex = WebUtils.getSessionMutex(session);
            synchronized (mutex) {
                return invokeHandlerMethod(request, response, handlerMethod);
            }
        }
    }
    // 关键 -> 3.处理器调用
    return invokeHandlerMethod(request, response, handlerMethod);
}
private ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response,HandlerMethod handlerMethod) throws Exception {
	ServletWebRequest webRequest = new ServletWebRequest(request, response);
	WebDataBinderFactory binderFactory = getDataBinderFactory(handlerMethod);
	ModelFactory modelFactory = getModelFactory(handlerMethod, binderFactory);
	ServletInvocableHandlerMethod requestMappingMethod = createRequestMappingMethod(handlerMethod, binderFactory);

	ModelAndViewContainer mavContainer = new ModelAndViewContainer();
	mavContainer.addAllAttributes(RequestContextUtils.getInputFlashMap(request));
	modelFactory.initModel(webRequest, mavContainer, requestMappingMethod);
	mavContainer.setIgnoreDefaultModelOnRedirect(this.ignoreDefaultModelOnRedirect);

        //执行Controller中的RequestMapping注释的方法  
	requestMappingMethod.invokeAndHandle(webRequest, mavContainer);
	modelFactory.updateModel(webRequest, mavContainer);

	if (mavContainer.isRequestHandled()) {
		return null;
	}
	else {
		ModelMap model = mavContainer.getModel();
                //返回ModelAndView视图  
		ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model);
		if (!mavContainer.isViewReference()) {
			mav.setView((View) mavContainer.getView());
		}
		if (model instanceof RedirectAttributes) {
			Map flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
			RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
		}
		return mav;
	}
}

RequestMappingHandlerAdapter其实简单来说就是采用反射机制调用url请求对应的Controller中的方法(这其中还包括参数处理等等操作没有介绍),返回执行结果值,这样就完成了HandlerAdapter的使命。

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。