美文网首页
HandlerAdapter

HandlerAdapter

作者: 回文体文回 | 来源:发表于2018-07-15 13:29 被阅读0次

前言

因为Handler格式是不固定的,所以在处理请求时需要HandlerAdapter做适配,我们再来回顾下HandlerAdapter的定义。

public interface HandlerAdapter {

    /**
     * 判断是否支持传入的handler
     */
    boolean supports(Object handler);

    /**
     * 使用给定的handler处理请求
     */
    ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;

    /**
     * 返回上次修改时间,可以返回-1表示不支持
     */
    long getLastModified(HttpServletRequest request, Object handler);

}

HandlerAdapter的实现有HttpRequestHandlerAdapter、SimpleServletHandlerAdapter、SimpleControllerHandlerAdapter、AnnotationMethodHandlerAdapter(已废弃)和RequestMappingHandlerAdapter,今天我们主要来分析下RequestMappingHandlerAdapter,因为RequestMappingHandlerAdapter使用的最多,其余的几个比较简单。

RequestMappingHandlerAdapter是和RequestMappingHandlerMapping配合使用的,我们先来看一下RequestMappingHandlerAdapter的继承关系图,然后再详细分析。

RequestMappingHandlerAdapter继承关系图

AbstractHandlerMethodAdapter

supports方法

AbstractHandlerMethodAdapter实现了supports方法,可以看出支持的Handler是HandlerMethod,另外还附加了一个判断方法supportsInternal,这个方法由RequestMappingHandlerAdapter实现,其就是简单地返回true。

    public final boolean supports(Object handler) {
        return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler));
    }
    protected boolean supportsInternal(HandlerMethod handlerMethod) {
        return true;
    }

handle方法

AbstractHandlerMethodAdapter实现了handle方法,就是简单地调用了模板方法handleInternal,handleInternal方法由RequestMappingHandlerAdapter实现。

    public final ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        return handleInternal(request, response, (HandlerMethod) handler);
    }

RequestMappingHandlerAdapter

初始化过程

RequestMappingHandlerAdapter实现了InitializingBean接口,所以它的初始化入口是afterPropertiesSet方法。

    public void afterPropertiesSet() {
        // Do this first, it may add ResponseBody advice beans
        initControllerAdviceCache();

        if (this.argumentResolvers == null) {
            List<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers();
            this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
        }
        if (this.initBinderArgumentResolvers == null) {
            List<HandlerMethodArgumentResolver> resolvers = getDefaultInitBinderArgumentResolvers();
            this.initBinderArgumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
        }
        if (this.returnValueHandlers == null) {
            List<HandlerMethodReturnValueHandler> handlers = getDefaultReturnValueHandlers();
            this.returnValueHandlers = new HandlerMethodReturnValueHandlerComposite().addHandlers(handlers);
        }
    }

可以看出主要是初始化了三个对象

  • argumentResolvers 用于给处理器方法和被@ModelAttribute注解的方法设置参数
  • initBinderArgumentResolvers 用于给被@InitBinder注解的方法设置参数
  • returnValueHandlers 用于将处理器返回值处理成ModelAndView类型

这里面又涉及了两个组件HandlerMethodArgumentResolver和HandlerMethodReturnValueHandler,这里我们不会具体深入的分析这两个组件,以后专门做讲解。

使用过程

从上面的分析我们知道使用的入口是handleInternal方法,可以看出最重要的一句是invokeHandlerMethod。

    protected ModelAndView handleInternal(HttpServletRequest request,
                                          HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {

        ModelAndView mav;
        // 检查HttpMethod是否支持,检查是否需要session
        checkRequest(request);

        // 需要同步session
        if (this.synchronizeOnSession) {
            HttpSession session = request.getSession(false);
            if (session != null) {
                Object mutex = WebUtils.getSessionMutex(session);
                synchronized (mutex) {
                    mav = invokeHandlerMethod(request, response, handlerMethod);
                }
            } else {
                mav = invokeHandlerMethod(request, response, handlerMethod);
            }
        } else {
            mav = invokeHandlerMethod(request, response, handlerMethod);
        }

        if (!response.containsHeader(HEADER_CACHE_CONTROL)) {
            if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {
                applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);
            } else {
                prepareResponse(response);
            }
        }

        return mav;
    }

下面我们来具体看下invokeHandlerMethod

    protected ModelAndView invokeHandlerMethod(HttpServletRequest request,
                                               HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {

        ServletWebRequest webRequest = new ServletWebRequest(request, response);
        try {
            WebDataBinderFactory binderFactory = getDataBinderFactory(handlerMethod);
            ModelFactory modelFactory = getModelFactory(handlerMethod, binderFactory);

            ServletInvocableHandlerMethod invocableMethod = createInvocableHandlerMethod(handlerMethod);
            invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
            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()) {
                Object result = asyncManager.getConcurrentResult();
                mavContainer = (ModelAndViewContainer) asyncManager.getConcurrentResultContext()[0];
                asyncManager.clearConcurrentResult();
                invocableMethod = invocableMethod.wrapConcurrentResult(result);
            }

            invocableMethod.invokeAndHandle(webRequest, mavContainer);
            if (asyncManager.isConcurrentHandlingStarted()) {
                return null;
            }

            return getModelAndView(mavContainer, modelFactory, webRequest);
        } finally {
            webRequest.requestCompleted();
        }
    }

这个方法非常复杂,我们先来解释下几个变量

  • WebDataBinderFactory 从名字就可以看出来是创建WebDataBinder用的,WebDataBinder用于参数绑定,主要用于参数与String之间的类型转换。

  • ModelFactory 用来处理Model,主要包含两个功能,1. 在Handler处理之前对Model初始化,2. 请求结束以后对Model参数进行更新

  • ServletInvocableHandlerMethod 它继承自HandlerMethod,并且可以直接执行,实际请求的处理就是通过它来执行的,参数绑定、处理请求以及返回值的处理都在里面完成

这三个变量创建完之后的工作还有三步(省略异步处理):

  1. 新建传递参数的ModelAndViewContainer容器,并将相应的参数设置到Model中

  2. 执行请求 invocableMethod.invokeAndHandle(webRequest, mavContainer);

3.请求完成后进行一些后置处理 getModelAndView(mavContainer, modelFactory, webRequest);

    public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer,
                                Object... providedArgs) throws Exception {

        // 处理请求
        Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);
        setResponseStatus(webRequest);

        if (returnValue == null) {
            if (isRequestNotModified(webRequest) || getResponseStatus() != null || mavContainer.isRequestHandled()) {
                mavContainer.setRequestHandled(true);
                return;
            }
        } else if (StringUtils.hasText(getResponseStatusReason())) {
            mavContainer.setRequestHandled(true);
            return;
        }

        mavContainer.setRequestHandled(false);
        try {
            // 使用ReturnValueHandler处理返回值
            this.returnValueHandlers.handleReturnValue(
                    returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
        } catch (Exception ex) {
            throw ex;
        }
    }
    public Object invokeForRequest(NativeWebRequest request, ModelAndViewContainer mavContainer,
                                   Object... providedArgs) throws Exception {

        // 处理得到方法参数
        Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
        // 调用方法处理请求
        Object returnValue = doInvoke(args);
        return returnValue;
    }
    // org.springframework.web.method.support.InvocableHandlerMethod
    private Object[] getMethodArgumentValues(NativeWebRequest request, ModelAndViewContainer mavContainer,
                                             Object... providedArgs) throws Exception {

        MethodParameter[] parameters = getMethodParameters();
        Object[] args = new Object[parameters.length];
        for (int i = 0; i < parameters.length; i++) {
            MethodParameter parameter = parameters[i];
            parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
            args[i] = resolveProvidedArgument(parameter, providedArgs);
            if (args[i] != null) {
                continue;
            }
            // 使用ArgumentResolver处理参数
            if (this.argumentResolvers.supportsParameter(parameter)) {
                try {
                    args[i] = this.argumentResolvers.resolveArgument(
                            parameter, mavContainer, request, this.dataBinderFactory);
                    continue;
                } catch (Exception ex) {
                    throw ex;
                }
            }
            if (args[i] == null) {
                throw new IllegalStateException("Could not resolve method parameter at index " +
                        parameter.getParameterIndex() + " in " + parameter.getMethod().toGenericString() +
                        ": " + getArgumentResolutionErrorMessage("No suitable resolver for", i));
            }
        }
        return args;
    }

相关文章

网友评论

      本文标题:HandlerAdapter

      本文链接:https://www.haomeiwen.com/subject/keoilftx.html