ContextLoader在初始化完成以后,Web容器就开始初始化DispatcherServlet,这个初始化的启动与在web.xml中对载入次序进行的定义有关。DipatcherServlet会建立自己的上下文来持有Spring MVC的Bean对象。这个建立对象的过程和ContexLoader是类似的,都是通过声明好的xml文件来注册声明好的bean对象。现在我们来具体看一下关于DispatcherServlet的启动和初始化
1.DispatcherSerlvet的初始化
DispatcherServlet的启动和Servlet的启动过程是相互联系的。所以在DispatcherServlet初始化的过程中也要调用init()方法
这个方法是在DispatcherServlet的父类HttpServletBean中找到的
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}
// Set bean properties from init parameters.
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}
// Let subclasses do whatever initialization they like.
initServletBean();
if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
首先从web.xml文件中读取到一些需要进行的配置属性,之后将需要的servlet进行实例化创建。
protected final void initServletBean() throws ServletException {
getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
if (this.logger.isInfoEnabled()) {
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
}
long startTime = System.currentTimeMillis();
try {
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
catch (ServletException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
catch (RuntimeException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
if (this.logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
elapsedTime + " ms");
}
}
在这个方法里面,首先进行了初始化上下文。也就是获取到WebApplicationContext。具体的取得上下文工作是在initWebApplicationContext();中进行体现的
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
可以看到使用的是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE这个值
public static WebApplicationContext getWebApplicationContext(ServletContext sc) {
return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
}
书上同样指出了如果当前没有WebApplicationContext需要创建一个,调用的是createWebApplicationContext方法。
可以看到在这个方法中,首先进行一些基本的配置,比如DispatcherServlet的双亲上下文,Bean定义配置的文件位置等。这些配置完成以后,就需要我们调用IoC容器的refresh方法来完成IoC容器的最终初始化。在我的实践中可以看到,它所初始化放置的有我们对于访问页面时的一些处理,比如字符集过滤器,比如文件上传控制器。还有就是那些我们注明了RequestMapping注解的Controller层文件。这些都在这个IoC容器中所持有,当我们在访问一个链接时就会查找相应的文件。这个留作下一篇博客说明
这样在初始化的过程中,DispatcherServlet就持有了一个以它自己的名字命名的IoC容器。既然DispatcherServlet的初始化已经完成。也就是说我们需要进行MVC的材料已经做好。那么进行MVC实现时还需要一些辅助的类。
2.DispatcherServlet的MVC初始化
书上是以HandlerMapping的初始化调用作为触发点的。那么我们就来看一下HandlerMapping的初始化
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
进入到initHandlerMappings方法中,HandlerMappings完成对MVC中Controller的定义和配置
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
}
else {
try {
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerMapping later.
}
}
// Ensure we have at least one HandlerMapping, by registering
// a default HandlerMapping if no other mappings are found.
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerMappings found in servlet '" + getServletName() + "': using default");
}
}
}
这个方法中首先导入说有的HandlerMapping Bean。这些Bean可以在当前的DispatcherServlet的IoC容器中,也可以在其双亲上下文中。HandlerMappings完成对MVC中Controller的定义和配置,只不过在Web这个特定的应用环境中,这些控制器是与具体的HTTP请求相对应的。
HandlerMapping定义了一个map,这个map表明了一系列的持有关系。也就是URL和我们的声明的Controller(我们将前端数据和后台业务逻辑进行结合的部分)的一个映射关系。这个映射关系通过HandlerMapping进行了封装。这个接口中定义了一个getHandler方法,通过这个方法,可以获得Http请求对应的HandlerExecutionChain,这个链中就封装了Controller对象
HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
关于HandlerMapping的作用我已经进行了说明,这是一个很重要的类。在Spring MVC的实现流程中,它起到了十分重要的作用。我们正是通过我们提交的URL找到了对应HandlerMapping,并通过这个HandlerMapping请求到了相应的方法。
下一篇博客我将讲述HandlerMapping的一些配置以及如何使用HandlerMapping完成请求的映射处理