首页 > 其他分享 >SpringMVC执行流程关键代码

SpringMVC执行流程关键代码

时间:2023-06-08 16:57:20浏览次数:49  
标签:... return SpringMVC 流程 request mavContainer handler HandlerMethod 代码

org.springframework.web.servlet.DispatcherServlet
protected void doDispatch(HttpServletRequest request, HttpServletResponse response)...
{
    // processedRequest 为 org.apache.catalina.connector.RequestFacade
    HttpServletRequest processedRequest = request;
    HandlerExecutionChain mappedHandler = null;
    ...

        ModelAndView mv = null;
            
            // HandlerExecutionChain with [com.chaixy.common.controller.TestController#test()] and 2 interceptors
            mappedHandler = getHandler(processedRequest);
            ...
            
            // org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter
            HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

            ...
            // 没有页面跳转 mv=null
            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

            ...

            applyDefaultViewName(processedRequest, mv);
            mappedHandler.applyPostHandle(processedRequest, response, mv);
    ...
}

protected HandlerExecutionChain getHandler(HttpServletRequest request)
{
    if (this.handlerMappings != null) {
        for (HandlerMapping mapping : this.handlerMappings) {
            // AbstractHandlerMapping
            HandlerExecutionChain handler = mapping.getHandler(request);
            if (handler != null) {
                return handler;
            }
        }
    }
    return null;
}



org.springframework.web.servlet.handler.AbstractHandlerMapping
public final HandlerExecutionChain getHandler(HttpServletRequest request)
{
    //com.chaixy.common.controller.TestController#test()
    Object handler = getHandlerInternal(request);
    ...
    HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
    
    ...
    return executionChain;
}

org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
    request.removeAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
    try {
        return super.getHandlerInternal(request);
    }
    finally {
        ProducesRequestCondition.clearMediaTypesAttribute(request);
    }
}



org.springframework.web.servlet.handler.AbstractHandlerMethodMapping
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
    String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
    request.setAttribute(LOOKUP_PATH, lookupPath);
    this.mappingRegistry.acquireReadLock();
    try {
        HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
        return ... handlerMethod.createWithResolvedBean() ...;
    }
    finally {
        this.mappingRegistry.releaseReadLock();
    }
}

protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request)
{
    List<Match> matches = new ArrayList<>();
    List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
    if (directPathMatches != null) {
        addMatchingMappings(directPathMatches, matches, request);
    }
    ...

        Match bestMatch = matches.get(0);
        ...
        request.setAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE, bestMatch.handlerMethod);
        handleMatch(bestMatch.mapping, lookupPath, request);
        return bestMatch.handlerMethod;
    ...
}

public HandlerMethod createWithResolvedBean() {
    Object handler = this.bean;
    if (this.bean instanceof String) {
        Assert.state(this.beanFactory != null, "Cannot resolve bean name without BeanFactory");
        String beanName = (String) this.bean;
        handler = this.beanFactory.getBean(beanName);
    }
    // this为com.chaixy.common.controller.TestController#test()
    // handler为com.chaixy.common.controller.TestController
    return new HandlerMethod(this, handler);
}



org.springframework.web.servlet.handler.AbstractHandlerMapping
protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) 
{
    // handler --> HandlerMethod com.chaixy.common.controller.TestController#test()
    // 走new HandlerExecutionChain(handler))
    HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ? 
        (HandlerExecutionChain) handler : new HandlerExecutionChain(handler));

    String lookupPath = this.urlPathHelper.getLookupPathForRequest(request, LOOKUP_PATH);
    for (HandlerInterceptor interceptor : this.adaptedInterceptors) {
        if (interceptor instanceof MappedInterceptor) {
            MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
            if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) {
                chain.addInterceptor(mappedInterceptor.getInterceptor());
            }
        }
        else {
            chain.addInterceptor(interceptor);
        }
    }
    // HandlerExecutionChain with [com.chaixy.common.controller.TestController#test()] and 2 interceptors
    return chain;
}



org.springframework.web.servlet.DispatcherServlet
protected HandlerAdapter getHandlerAdapter(Object handler)
{
        for (HandlerAdapter adapter : this.handlerAdapters) {
            if (adapter.supports(handler)) {
                // org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
                return adapter;
            }
        }
    ...
}


org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter#supports
public final boolean supports(Object handler) {
    return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler));
}

org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#supportsInternal
protected boolean supportsInternal(HandlerMethod handlerMethod) {
    return true;
}




org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter#handle
public final ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
{
    return handleInternal(request, response, (HandlerMethod) handler);
}

org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#handleInternal
protected ModelAndView handleInternal(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod)
{
    ModelAndView mav;

    ...
        mav = invokeHandlerMethod(request, response, handlerMethod);
    ...

    return mav;
}

protected 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 invocableMethod = 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()) {
            Object result = asyncManager.getConcurrentResult();
            mavContainer = (ModelAndViewContainer) asyncManager.getConcurrentResultContext()[0];
            asyncManager.clearConcurrentResult();
            LogFormatUtils.traceDebug(logger, traceOn -> {
                String formatted = LogFormatUtils.formatValue(result, !traceOn);
                return "Resume with async result [" + formatted + "]";
            });
            invocableMethod = invocableMethod.wrapConcurrentResult(result);
        }
        // 重要! 重要! 重要! 在这里反射调用Controller里面的业务代码
        invocableMethod.invokeAndHandle(webRequest, mavContainer);

        return getModelAndView(mavContainer, modelFactory, webRequest);
    ...
}

private ModelAndView getModelAndView(ModelAndViewContainer mavContainer,
        ModelFactory modelFactory, NativeWebRequest webRequest)
{
    modelFactory.updateModel(webRequest, mavContainer);
    if (mavContainer.isRequestHandled()) {
        // 直接返回null
        return null;
    }
    ModelMap model = mavContainer.getModel();
    ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, mavContainer.getStatus());
    if (!mavContainer.isViewReference()) {
        mav.setView((View) mavContainer.getView());
    }
    if (model instanceof RedirectAttributes) {
        Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        if (request != null) {
            RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
        }
    }
    return mav;
}

 

标签:...,return,SpringMVC,流程,request,mavContainer,handler,HandlerMethod,代码
From: https://www.cnblogs.com/dzpykj/p/17466992.html

相关文章

  • springmvc加文件上传支持
     找个sping.xml之类的,加入配置以及引用<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> <dependency><groupId>commons-fileupload</groupId>......
  • 点到点和图到图带代码
    点到点的代码理解点击查看代码defload_train_data_for_rnn(cfg,x,y,aux,scaler):#x={nt,nf,ngrid}={3287,9,1399}#y={nt,ngrid}={3287,1399}#aux={nf,nt}={1,1399}#scaler={2,45,90,1}nt,nf,ngrid=x.shape......
  • Linux 安装git,并且使用https方式 git pull 代码的免密操作
    删除系统自带的gityumremovegit去git下载对应安装包https://github.com/git/git/releaseswgethttps://github.com/git/git/archive/v2.21.0.tar.gz安装依赖yum-yinstallcurl-develexpat-develgettext-developenssl-develzlib-develgccperl-ExtUtils-MakeMaker解压tar......
  • 国产低代码平台哪家强?
    低代码开发平台的优势更快的开发速度:低代码平台允许开发人员使用图形化界面进行应用程序开发,从而大大缩短了开发时间。开发人员不再需要手写代码,而是利用平台提供的组件和模板快速构建应用程序。更低的成本:低代码开发平台可以减少开发和部署的成本。由于不需要手写代码,开发人员可......
  • 联邦学习算法介绍-FedAvg详细案例-Python代码获取
    联邦学习算法介绍-FedAvg详细案例-Python代码获取一、联邦学习系统框架二、联邦平均算法(FedAvg)三、联邦随梯度下降算法(FedSGD)四、差分隐私随联邦梯度下降算法(DP-FedSGD)五、差分隐私联邦平均算法(DP-FedAVG)六、FedAVG案例附代码1)案例背景2)参数设置3)结果展示4)代码详解七、完整......
  • python 安装包、基础学习资料、代码应用示例
    安装包python-3.7.0.rar链接:https://pan.baidu.com/s/1Gl5QUMrLFoTekENighd0iw提取码:ysgxpycharm5.0.3.zip链接:https://pan.baidu.com/s/1DpzRiMWSW2byWjB1cYmQKw提取码:9rgiAnaconda3jupyternotebook第一步进入:https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/第......
  • 基于springmvc+spring+mybatis+hibernate 封装的框架
    基于maven  freemarker2.3.20  spirngmvc3.2.9.RELEASE  spring3.2.9.RELEASE  Hiberante3.6.9.Final(自动建表)  mybatis3.2.7数据交互  druid连接池   cxf3.0.0发布webservice  quartz2.2.1定时任务  jquery   jquery-datata......
  • 进入流程化管理不再是奢望,开源快速开发框架助你梦想成真!
    在数字化进程快速发展的今天,流程化管理是企业做强做大的重要一步。如何实现流程化管理?如何实现数字化发展目标?这些问题都是值得每一个企业深思的重要课题。开源快速开发框架是一种快速帮助企业提质增效的平台软件,可以让每一个企业的流程化管理梦想照进现实。想进入流程化管理吗?一......
  • .NET代码审计XSS篇-Html.Raw
    在.NETMVC项目中,默认创建的视图,都是以cshtml为后缀的Razor视图,这种视图通常以.cshtml文件扩展名,Razor视图引擎对自动对输出的内容进行HTML编码,这些字符会被编码成HTML实体,如图1如果确实某些场景需要在视图中显示原始HTML内容,而不进行HTML编码,可以使用Html.Raw方法。Html.Raw标......
  • goland不提交git,同步代码到开发机,设置步骤
    1.Tools->Deployment->Configuration    2.Tools->Deployment->Uploadxxx ......