您的位置:首页 > 编程语言 > Java开发

Spring Web MVC的实现

2010-10-15 16:38 435 查看
关于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代码 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);
}
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代码 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;
}
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; }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: