DispathcerServlet初始化之HanddlerMapping、HandlerAdapter初始化

在SpringMVC框架中,DispatcherServlet负责接收所有的HTTP请求并将其分发给相应的处理器。在初始化过程中,DispatcherServlet会加载和初始化所有的HandlerMapping和HandlerAdapter,以便在处理请求时能够找到合适的处理器方法并调用它。

以下是DispatcherServlet初始化之HandlerMapping和HandlerAdapter的步骤,并通过代码进行说明:

1、加载HandlerMapping:在SpringMVC中,HandlerMapping负责将请求映射到相应的处理器方法。DispatcherServlet在初始化过程中,会加载配置文件中定义的HandlerMapping。例如,在XML配置文件中,可以使用<bean>元素来定义一个HandlerMapping:

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />

在上面的配置中,定义了一个BeanNameUrlHandlerMapping处理器映射器。

2、初始化HandlerMapping:加载HandlerMapping后,DispatcherServlet会初始化所有的HandlerMapping。在初始化过程中,会遍历所有的HandlerMapping,并为它们创建相应的HandlerExecutionChain对象。HandlerExecutionChain对象是一个封装了处理器方法和拦截器链的对象,用于在处理请求时依次调用拦截器和处理器方法。例如,以下代码演示了如何初始化一个BeanNameUrlHandlerMapping对象:

@Override  
public void initApplicationContext() throws BeansException {  
    super.initApplicationContext();  
    initHandlerMappings();  
}  
  
private void initHandlerMappings() {  
    for (HandlerMapping hm : this.handlerMappings) {  
        if (logger.isDebugEnabled()) {  
            logger.debug("Initializing " + hm + "");  
        }  
        hm.initApplicationContext();  
    }  
}

在上面的代码中,首先通过调用父类的initApplicationContext()方法来初始化Spring容器。然后,通过遍历handlerMappings集合中的所有HandlerMapping对象,并调用它们的initApplicationContext()方法来初始化它们。在BeanNameUrlHandlerMapping中,initApplicationContext()方法会将所有的Bean名称和URL路径映射到相应的HandlerExecutionChain对象中。

3、加载HandlerAdapter:在SpringMVC中,HandlerAdapter负责调用处理器方法并处理返回值。DispatcherServlet在初始化过程中,会加载配置文件中定义的HandlerAdapter。例如,在XML配置文件中,可以使用<bean>元素来定义一个HandlerAdapter:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />

在上面的配置中,定义了一个RequestMappingHandlerAdapter处理器适配器。

4、初始化HandlerAdapter:加载HandlerAdapter后,DispatcherServlet会初始化所有的HandlerAdapter。在初始化过程中,会遍历所有的HandlerAdapter,并为它们创建相应的处理器适配器对象。例如,以下代码演示了如何初始化一个RequestMappingHandlerAdapter对象:

@Override  
public void initApplicationContext() throws BeansException {  
    super.initApplicationContext();  
    initHandlerAdapters();  
}  
  
private void initHandlerAdapters() {  
    for (HandlerAdapter ha : this.handlerAdapters) {  
        if (logger.isDebugEnabled()) {  
            logger.debug("Initializing " + ha + "");  
        }  
        ha.initApplicationContext();  
    }  
}

 在上面的代码中,首先通过调用父类的initApplicationContext()方法来初始化Spring容器。然后,通过遍历handlerAdapters集合中的所有HandlerAdapter对象,并调用它们的initApplicationContext()方法来初始化它们。在RequestMappingHandlerAdapter中,initApplicationContext()方法会将所有的RequestMappingInfo对象和HandlerMethod对象映射到相应的处理器适配器对象中。这样,在处理请求时,就可以通过RequestMappingInfo对象找到相应的处理器适配器对象,并通过处理器适配器对象调用相应的处理器方法。

猜你喜欢

转载自blog.csdn.net/weixin_52721608/article/details/133491350