`
Donald_Draper
  • 浏览: 984760 次
社区版块
存档分类
最新评论

Spring-DispatcherServlet请求处理

阅读更多
Spring-DispatcherServlet初始化详解:http://donald-draper.iteye.com/blog/2325394
Spring的DefaultAnnotationHandlerMapping详解:http://donald-draper.iteye.com/blog/2325453
前面我们已经探究过DispatcherServlet的初始化,下面我们来看看
DispatcherServlet如何处理web请求
//DispatcherServlet
 public class DispatcherServlet extends FrameworkServlet
{
}

从DispatcherServlet我们看不到任何请求处理入口再来看FrameworkServlet
public abstract class FrameworkServlet extends HttpServletBean
    implements ApplicationContextAware
{
 public FrameworkServlet(WebApplicationContext webApplicationContext)
    {
        contextClass = DEFAULT_CONTEXT_CLASS;
        contextInitializers = new ArrayList();
        publishContext = true;
        publishEvents = true;
        threadContextInheritable = false;
        dispatchOptionsRequest = false;
        dispatchTraceRequest = false;
        webApplicationContextInjected = false;
        refreshEventReceived = false;
        this.webApplicationContext = webApplicationContext;
    }
    //在这里我们发现了处理请求的方法,默认方法
     protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        String method = request.getMethod();
        if(method.equalsIgnoreCase(RequestMethod.PATCH.name()))
            processRequest(request, response);
        else
            super.service(request, response);
    }
    //GET
    protected final void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        processRequest(request, response);
    }
    //POST
    protected final void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        processRequest(request, response);
    }
    //PUT
    protected final void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        processRequest(request, response);
    }
    //DELETE
    protected final void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        processRequest(request, response);
    }
    //实际处理请求方法
    protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        try
        {
	   //处理请求
            doService(request, response);
        }
    }
    //带子类DispatcherServlet扩展
     protected abstract void doService(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)
        throws Exception;
    public static final String DEFAULT_NAMESPACE_SUFFIX = "-servlet";
    public static final Class DEFAULT_CONTEXT_CLASS = org/springframework/web/context/support/XmlWebApplicationContext;
    public static final String SERVLET_CONTEXT_PREFIX = (new StringBuilder()).append(org/springframework/web/servlet/FrameworkServlet.getName()).append(".CONTEXT.").toString();
    private static final String INIT_PARAM_DELIMITERS = ",; \t\n";
    private String contextAttribute;
    private Class contextClass;
    private String contextId;
    private String namespace;
    private String contextConfigLocation;
    private final ArrayList contextInitializers;
    private String contextInitializerClasses;
    private boolean publishContext;
    private boolean publishEvents;
    private boolean threadContextInheritable;
    private boolean dispatchOptionsRequest;
    private boolean dispatchTraceRequest;
    private WebApplicationContext webApplicationContext;
    private boolean webApplicationContextInjected;
    private boolean refreshEventReceived;
}

我们来看DispatcherServlet
public class DispatcherServlet extends FrameworkServlet
{
 public DispatcherServlet(WebApplicationContext webApplicationContext)
    {
        super(webApplicationContext);
        detectAllHandlerMappings = true;
        detectAllHandlerAdapters = true;
        detectAllHandlerExceptionResolvers = true;
        detectAllViewResolvers = true;
        throwExceptionIfNoHandlerFound = false;
        cleanupAfterInclude = true;
    }
    //处理请求
     protected void doService(HttpServletRequest request, HttpServletResponse response)
        throws Exception
    {
        //设置请求属性,web上下文,本地化,主题
        request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
        request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, localeResolver);
        request.setAttribute(THEME_RESOLVER_ATTRIBUTE, themeResolver);
        request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());
        FlashMap inputFlashMap = flashMapManager.retrieveAndUpdate(request, response);
        if(inputFlashMap != null)
            request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
        request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
        request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, flashMapManager);
	//委托给doDispatch
        doDispatch(request, response);
        
    }

    protected void doDispatch(HttpServletRequest request, HttpServletResponse response)
        throws Exception
    {
        HttpServletRequest processedRequest;
        HandlerExecutionChain mappedHandler;
        boolean multipartRequestParsed;
        WebAsyncManager asyncManager;
        processedRequest = request;
        mappedHandler = null;
        multipartRequestParsed = false;
        asyncManager = WebAsyncUtils.getAsyncManager(request);
        ModelAndView mv;
        Exception dispatchException;
        mv = null;
        dispatchException = null;
        processedRequest = checkMultipart(request);
        multipartRequestParsed = processedRequest != request;
	//获取控制器处理器链
        mappedHandler = getHandler(processedRequest);
        HandlerAdapter ha;
        //获取控制器方法适配器
        ha = getHandlerAdapter(mappedHandler.getHandler());
	//获取处理视图
        mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
	//返回视图
        applyDefaultViewName(request, mv);
    }
   //获取控制器处理器链
   protected HandlerExecutionChain getHandler(HttpServletRequest request)
        throws Exception
    {   
       //List<HashMap<String,HandlerMapping>>
        for(Iterator iterator = handlerMappings.iterator(); iterator.hasNext();)
        { 
            HandlerMapping hm = (HandlerMapping)iterator.next();
            if(logger.isTraceEnabled())
                logger.trace((new StringBuilder()).append("Testing handler map [").append(hm).append("] in DispatcherServlet with name '").append(getServletName()).append("'").toString());
            HandlerExecutionChain handler = hm.getHandler(request);
            if(handler != null)
                return handler;
        }
    }
    //获取控制器方法适配器
    protected HandlerAdapter getHandlerAdapter(Object handler)
        throws ServletException
    {
        //List<HashMap<String,HandlerAdapter>>
        for(Iterator iterator = handlerAdapters.iterator(); iterator.hasNext();)
        {
            HandlerAdapter ha = (HandlerAdapter)iterator.next();
            if(logger.isTraceEnabled())
                logger.trace((new StringBuilder()).append("Testing handler adapter [").append(ha).append("]").toString());
            if(ha.supports(handler))
                return ha;
        }
    }
    private List handlerMappings;//List<HashMap<String,HandlerMapping>>,Key为beanName,value值为HandlerMapping实例
    private List handlerAdapters;//List<HashMap<String,HandlerAdapter>>,Key为beanName,value值为HandlerAdapter实例
    private List handlerExceptionResolvers;
    private List viewResolvers;

    static 
    {
        try
        {
	    //加载默认配置文件
            ClassPathResource resource = new ClassPathResource("DispatcherServlet.properties", org/springframework/web/servlet/DispatcherServlet);
            defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
        }
    }
}

总结:
DispatcherServlet处理请求实际上是通过FrameworkServlet的Service()和do*类方法,
而这些方式实际的处理逻辑在DispatcherServlet的doService和doDispatch中,doDispatch
先找出控制器处理器,然后再找出控制器方法适配器,通过控制器方法适配器,来处理具体请求。
0
0
分享到:
评论

相关推荐

    spring-web-5.2.3.RELEASE和spring-webmvc-5.2.3.RELEASE

    在Spring Web MVC中,DispatcherServlet是核心组件,它负责接收HTTP请求,根据请求映射找到对应的处理器(Controller),并调用处理器完成业务逻辑。然后,处理器可以通过ModelAndView对象返回视图和模型数据。 在...

    SpringMVC源码剖析(四)- DispatcherServlet请求转发的实现1

    在`doGet()`方法中,Spring MVC并没有直接处理请求,而是调用了`processRequest()`方法,这是DispatcherServlet的父类`FrameworkServlet`中的抽象方法。这个方法是整个请求处理流程的起点。在`processRequest()`内部...

    spring-mybatis-spring-1.3.2.tar.gz

    1. DispatcherServlet配置:在web.xml中配置DispatcherServlet,它是SpringMVC的前端控制器,负责接收请求并分发给处理器。 2. Controller定义:创建@Controller注解的类,实现业务逻辑,使用@RequestMapping注解...

    搭建SSH框架需要引入的Struts2包(log4j,spring-web,struts2-spring-plugin)

    Spring Web模块包含了Servlet监听器、过滤器、DispatcherServlet等核心组件,它们协同工作以接收请求、解析请求参数、执行业务逻辑并返回响应。此外,Spring还提供了事务管理、数据访问/集成、AOP等功能,极大地增强...

    spring-web.jar spring-webmvc.jar

    1. **DispatcherServlet**:作为Spring MVC的核心,`DispatcherServlet`负责拦截所有到达的HTTP请求,然后根据请求映射找到合适的处理器(控制器)进行处理。 2. **控制器**:开发者可以定义控制器类,这些类处理...

    spring.jar spring-webmvc-struts.jar spring-webmvc.jar

    3. **Spring MVC**:学习Spring MVC的架构,包括DispatcherServlet、Controller、Model、View、ModelAndView等概念,以及请求处理流程。 4. **Struts集成**:如果使用了spring-webmvc-struts.jar,需要了解如何在...

    spring-web和spring-webmvc_4.2.4

    2. **DispatcherServlet**:作为Spring MVC的前端控制器,它负责接收请求、调度请求到相应的处理器,并最终将结果返回给客户端。 3. **HandlerMapping**与**HandlerAdapter**:这两个组件负责映射HTTP请求到对应的...

    spring-web.jar

    1. DispatcherServlet:作为Spring MVC的核心,DispatcherServlet负责接收HTTP请求,根据请求信息找到合适的处理器(Controller),并调度执行。它通过配置可以拦截所有HTTP请求,实现统一的入口。 2. ...

    Spring-MVC-DispatcherServlet-Example:Maven项目

    1. **DispatcherServlet** - 负责请求分发,它是Spring MVC的入口点。当Web服务器接收到请求时,DispatcherServlet会拦截请求,然后根据请求映射信息找到对应的处理器(Controller)。 2. **Controller** - 控制器...

    网上书城 spring-mvc

    1. **DispatcherServlet**:作为Spring-MVC的前端控制器,它接收所有HTTP请求,并根据配置的映射规则转发给相应的处理器。 2. **Model-View-Controller (MVC)架构**:这是一种设计模式,将业务逻辑(Model)、用户...

    spring-web-3.1.1.RELEASE.jar.zip

    Spring Web模块是Spring框架的重要组成部分,它为构建RESTful服务、处理HTTP请求、集成Servlet容器等提供了便利。该模块包含以下几个关键组件: 1. `DispatcherServlet`:作为Spring MVC的入口点,负责接收HTTP请求...

    spring-webmvc-5.0.9 jar包、源码和javadoc

    它通过DispatcherServlet作为请求分发器,处理来自客户端的HTTP请求,并将请求转发给相应的处理器,如控制器(Controller)。 二、DispatcherServlet DispatcherServlet是Spring MVC的前端控制器,负责接收HTTP请求...

    spring-web-5.2.4_spring-web_SSM框架_

    SSM框架中的Spring Web扮演着至关重要的角色,它作为整个SSM架构的入口,负责处理来自用户的请求,并通过Spring的依赖注入和AOP特性,与其他组件如Spring Core、Spring JDBC、Spring ORM等协同工作,为开发者提供一...

    spring-mvc-showcase

    `@RequestMapping`注解是Spring MVC中用于映射HTTP请求的关键注解,它可以应用于类或方法上,指定处理请求的URL路径、HTTP方法等。HandlerMapping组件则负责根据这些映射信息找到合适的Controller方法。 五、...

    spring-mvc jar包

    DispatcherServlet作为入口,负责接收HTTP请求并调度处理。Controller处理业务逻辑,ViewResolver解析视图,而ModelAndView则封装了模型数据和视图信息。 在Spring MVC中,我们可以通过注解来简化控制器的编写,如@...

    spring-mvc-study.zip

    首先,Spring MVC是Spring框架的一个模块,主要用于处理HTTP请求和响应。它的主要组件包括DispatcherServlet、Controller、Model、View和ViewModel。DispatcherServlet作为前端控制器,负责接收请求并分发到相应的...

    spring-webmvc-struts.jar

    1. **DispatcherServlet**:Spring MVC的前端控制器,负责接收HTTP请求,然后根据请求信息找到相应的处理器(Controller)进行处理。 2. **Model-View-Controller**:模型-视图-控制器架构,Spring MVC的核心设计...

    Spring-MVC+Spring-IOC+Spring-JdbcTemple

    1. **Spring MVC的请求处理流程**:从DispatcherServlet开始,如何通过HandlerMapping找到对应的Controller,再到HandlerAdapter执行方法,最后由ViewResolver返回视图。 2. **Spring Bean的生命周期**:了解Bean的...

    spring-mvc-demo

    - **DispatcherServlet**:Spring MVC 的入口点,负责处理所有的 HTTP 请求,并根据请求映射信息分发到相应的处理器。 - **Controller**:控制器类,用于处理用户请求,通常以注解方式定义,如 `@RequestMapping`...

    spring-mvc-官方中文文档

    Spring MVC 提供了丰富的功能,包括请求处理、视图解析、数据绑定、异常处理等,旨在简化 Web 开发流程。 1. **Spring MVC 概述**:Spring MVC 是基于 Spring 框架构建的,它遵循 MVC 设计模式,将业务逻辑、数据和...

Global site tag (gtag.js) - Google Analytics