Spring Web MVC的实现

关于MVC,这是和WEB开发相关的部分,显然大家都是很熟悉了。从最初的JSP到struts,再到像wicket等等,真是百花齐放,百家争鸣.在 WEB UI上,这部分是做web应用架构选择不可缺少的一部分。而作为MVC框架,也许SPRING MVC不能算得上是表现力最出色的UI框架,但无疑,它的实现也是非常的优秀,同时,我们可以从它的实现上,看到一个非常清晰的MVC实现的过程,从这点 上看,真是非常的过瘾啊!

在了解IOC容器的基本实现的基础上,下面我们来看看,在典型的Web环境中,Spring IOC容器是如何在Web环境中被载入并起作用的。我们可以看到,对于MVC这部分,主要建立在IOC的基础上,AOP的特性应用得并不多。Spring 并不是天生就能在Web容器中起作用的,同样也需要一个启动过程,把自己的IOC容器导入,并在Web容器中建立起来。

与对IoC容器的初始化的分析一样,我们同样看到了loadBeanDefinition对BeanDefinition的载入。在Web环境 中,对定位BeanDefinition的Resource有特别的要求,对这个要求的处理体现在getDefaultConfigLocations方 法的处理中。可以看到,在这里,使用了默认的BeanDefinition的配置路径,这个路径在XmlWebApplicationContext中, 已经作为一个常量定义好了,这个常量就是/WEB-INF/applicationContext.xml。这里的loadBeanDefinition 实现如下所示:

Java代码
  1. public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {  
  2.   
  3.     /** Default config location for the root context */  
  4.     //这里是设置缺省BeanDefinition的地方,在/WEB-INF/applicationContext.xml文件里,如果不特殊指定其他文件,IoC容器会从这里读取BeanDefinition来初始化IoC容器  
  5.     public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";  
  6.   
  7.     /** Default prefix for building a config location for a namespace */  
  8.     public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";  
  9.   
  10.     /** Default suffix for building a config location for a namespace */  
  11.     public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";  
  12.     //我们又看到了熟悉的loadBeanDefinition,就像我们前面对IOC容器的分析一样,这个加载过程在容器refresh()时启动。  
  13.     protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {  
  14.         // Create a new XmlBeanDefinitionReader for the given BeanFactory.  
  15.         // 对于XmlWebApplicationContext,当然是使用XmlBeanDefinitionReader来对BeanDefinition信息进行解析  
  16.         XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);  
  17.   
  18.         // Configure the bean definition reader with this context's  
  19.         // resource loading environment.  
  20.         // 这里设置ResourceLoader,因为XmlWebApplicationContext是DefaultResource的子类,所以这里同样会使用DefaultResourceLoader来定位BeanDefinition       
  21.         beanDefinitionReader.setResourceLoader(this);  
  22.         beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));  
  23.   
  24.         // Allow a subclass to provide custom initialization of the reader,  
  25.         // then proceed with actually loading the bean definitions.  
  26.         initBeanDefinitionReader(beanDefinitionReader);  
  27.         //这里使用定义好的XmlBeanDefinitionReader来载入BeanDefinition  
  28.         loadBeanDefinitions(beanDefinitionReader);  
  29.     }  
  30.   
  31.   
  32.     protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {  
  33.     }  
  34.   
  35.   
  36.     //如果有多个BeanDefinition的文件定义,需要逐个载入,都是通过reader来完成的,这个初始化过程是由refreshBeanFactory方法来完成的,这里只是负责载入BeanDefinition  
  37.     protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {  
  38.         String[] configLocations = getConfigLocations();  
  39.         if (configLocations != null) {  
  40.             for (String configLocation : configLocations) {  
  41.                 reader.loadBeanDefinitions(configLocation);  
  42.             }  
public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext { /** Default config location for the root context */ //这里是设置缺省BeanDefinition的地方,在/WEB-INF/applicationContext.xml文件里,如果不特殊指定其他文件,IoC容器会从这里读取BeanDefinition来初始化IoC容器 public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml"; /** Default prefix for building a config location for a namespace */ public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/"; /** Default suffix for building a config location for a namespace */ public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml"; //我们又看到了熟悉的loadBeanDefinition,就像我们前面对IOC容器的分析一样,这个加载过程在容器refresh()时启动。 protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. // 对于XmlWebApplicationContext,当然是使用XmlBeanDefinitionReader来对BeanDefinition信息进行解析 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. // 这里设置ResourceLoader,因为XmlWebApplicationContext是DefaultResource的子类,所以这里同样会使用DefaultResourceLoader来定位BeanDefinition beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. initBeanDefinitionReader(beanDefinitionReader); //这里使用定义好的XmlBeanDefinitionReader来载入BeanDefinition loadBeanDefinitions(beanDefinitionReader); } protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) { } //如果有多个BeanDefinition的文件定义,需要逐个载入,都是通过reader来完成的,这个初始化过程是由refreshBeanFactory方法来完成的,这里只是负责载入BeanDefinition protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { String[] configLocations = getConfigLocations(); if (configLocations != null) { for (String configLocation : configLocations) { reader.loadBeanDefinitions(configLocation); }

进入DispatcherServlet和MVC实现
完成了在Web环境中,IoC容器的建立以后,也就是在完成对ContextLoaderListener的初始化以后,Web容器开始初始化 DispatcherServlet,接着,会执行DispatcherServlet持有的IoC容器的初始化过程,在这个初始化过程中,一个新的上下 文被建立起来,这个DispatcherServlet持有的上下文,被设置为根上下文的子上下文。可以大致认为,根上下文是和Web应用相对应的一个上 下文,而DispatcherServlet持有的上下文是和Servlet对应的一个上下文,在一个Web应用中,往往可以容纳多个Servlet存 在;与此相对应,对于应用在Web容器中的上下体系,也是很类似的,一个根上下文可以作为许多Servlet上下文的双亲上下文。在 DispatcherServlet,我们可以看到对MVC的初始化,是在DispatcherServlet的initStrategies完成的。
在这个初始化完成以后,会在上下文中建立器一个执行器于url的对应关系,这个对应关系可以让在url请求到来的时候,MVC可以检索到相应的控制器来进行处理,如以下代码所示:
Java代码
  1. protected Object getHandlerInternal(HttpServletRequest request) throws Exception {  
  2.     //这里从request中得到请求的url路径  
  3.     String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);  
  4.     //这里使用得到的url路径对Handler进行匹配,得到对应的Handler,如果没有对应的Hanlder,返回null,这样默认的Handler会被使用  
  5.     Object handler = lookupHandler(lookupPath, request);  
  6.     if (handler == null) {  
  7.         // We need to care for the default handler directly, since we need to  
  8.         // expose the PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE for it as well.  
  9.         Object rawHandler = null;  
  10.         if ("/".equals(lookupPath)) {  
  11.             rawHandler = getRootHandler();  
  12.         }  
  13.         if (rawHandler == null) {  
  14.             rawHandler = getDefaultHandler();  
  15.         }  
  16.         if (rawHandler != null) {  
  17.             validateHandler(rawHandler, request);  
  18.             handler = buildPathExposingHandler(rawHandler, lookupPath, null);  
  19.         }  
  20.     }  
  21.     if (handler != null && logger.isDebugEnabled()) {  
  22.         logger.debug("Mapping [" + lookupPath + "] to handler '" + handler + "'");  
  23.     }  
  24.     else if (handler == null && logger.isTraceEnabled()) {  
  25.         logger.trace("No handler mapping found for [" + lookupPath + "]");  
  26.     }  
  27.     return handler;  
  28. }  
  29.   // lookupHandler是根据url路径,启动在handlerMap中对handler的检索,并最终返回handler对象  
  30. protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception {  
  31.     // Direct match?  
  32.     Object handler = this.handlerMap.get(urlPath);  
  33.     if (handler != null) {  
  34.         validateHandler(handler, request);  
  35.         return buildPathExposingHandler(handler, urlPath, null);  
  36.     }  
  37.     // Pattern match?  
  38.     String bestPathMatch = null;  
  39.     for (String registeredPath : this.handlerMap.keySet()) {  
  40.         if (getPathMatcher().match(registeredPath, urlPath) &&  
  41.                 (bestPathMatch == null || bestPathMatch.length() < registeredPath.length())) {  
  42.             bestPathMatch = registeredPath;  
  43.         }  
  44.     }  
  45.     if (bestPathMatch != null) {  
  46.         handler = this.handlerMap.get(bestPathMatch);  
  47.         validateHandler(handler, request);  
  48.         String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestPathMatch, urlPath);  
  49.         Map<String, String> uriTemplateVariables =  
  50.                 getPathMatcher().extractUriTemplateVariables(bestPathMatch, urlPath);  
  51.         return buildPathExposingHandler(handler, pathWithinMapping, uriTemplateVariables);  
  52.     }  
  53.     // No handler found...  
  54.     return null;  
  55. }  
protected Object getHandlerInternal(HttpServletRequest request) throws Exception { //这里从request中得到请求的url路径 String lookupPath = this.urlPathHelper.getLookupPathForRequest(request); //这里使用得到的url路径对Handler进行匹配,得到对应的Handler,如果没有对应的Hanlder,返回null,这样默认的Handler会被使用 Object handler = lookupHandler(lookupPath, request); if (handler == null) { // We need to care for the default handler directly, since we need to // expose the PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE for it as well. Object rawHandler = null; if ("/".equals(lookupPath)) { rawHandler = getRootHandler(); } if (rawHandler == null) { rawHandler = getDefaultHandler(); } if (rawHandler != null) { validateHandler(rawHandler, request); handler = buildPathExposingHandler(rawHandler, lookupPath, null); } } if (handler != null && logger.isDebugEnabled()) { logger.debug("Mapping [" + lookupPath + "] to handler '" + handler + "'"); } else if (handler == null && logger.isTraceEnabled()) { logger.trace("No handler mapping found for [" + lookupPath + "]"); } return handler; } // lookupHandler是根据url路径,启动在handlerMap中对handler的检索,并最终返回handler对象 protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception { // Direct match? Object handler = this.handlerMap.get(urlPath); if (handler != null) { validateHandler(handler, request); return buildPathExposingHandler(handler, urlPath, null); } // Pattern match? String bestPathMatch = null; for (String registeredPath : this.handlerMap.keySet()) { if (getPathMatcher().match(registeredPath, urlPath) && (bestPathMatch == null || bestPathMatch.length() < registeredPath.length())) { bestPathMatch = registeredPath; } } if (bestPathMatch != null) { handler = this.handlerMap.get(bestPathMatch); validateHandler(handler, request); String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestPathMatch, urlPath); Map<String, String> uriTemplateVariables = getPathMatcher().extractUriTemplateVariables(bestPathMatch, urlPath); return buildPathExposingHandler(handler, pathWithinMapping, uriTemplateVariables); } // No handler found... return null; }

posted on 2010-10-15 16:38  画一个圆圈  阅读(142)  评论(0编辑  收藏  举报

导航