相信你们都可以在上网上看到Spring MVC的核心类其实就是DispatherServlet,也就是Spring MVC处理请求的核心分发器。其实核心分发器几乎是全部MVC框架设计中的核心概念,像在Struts2也有相似的分发器FilterDispatcher。只不过Spring MVC中的是一个Servlet,而Struts2里面的是一个Filter.既然咱们知道了Spring MVC的中核心类DispatcherServlet是一个Servlet。下面咱们就来了解一下Servlet相关的概念。以助于咱们后面分析Spring MVC的总体框架。前端
一、Servlet容器的加载顺序web
相信大多数写Java Web程序的都接触过web.xml这个配置文件。下面咱们就来看一下里面最主要的几个元素。spring
context-param : 对于全部Servlet均可用的全局变量,被封装于ServletContext时。缓存
listener : 基于观察者模式设计的,用于对开发Servlet应用程序提供了一种快捷的手段,可以方便的从另外一个纵向维度控制程序和数据。bash
filter : 用于拦截Servlet,能够在调用Servlet以前或者以后修改Servlet中Request或者Response的值。数据结构
servlet : 用于监听并处理全部的Web请求。在service及其相关方法中对Http请求的处理流程。架构
这里是Servlet容器中咱们使用到最多的几个元素。它们在Servlet里面的初始化顺序以下:app
context-param –> listener -> filter -> servlet
复制代码
具体能够参见:web.xml 初始化顺序框架
二、Servlet的生命周期webapp
了解了Servlet里面的主要元素的加载顺序,下面咱们就来看一下Servlet里面的生命周期:
public interface Servlet {
public void init(ServletConfig config) throws ServletException;
public ServletConfig getServletConfig();
public void service(ServletRequest req, ServletResponse res)
throwsServletException;, IOException;
public String getServletInfo();
public void destroy();
}
复制代码
咱们能够看到在Servlet接口里面有5个方面。
init():Servlet的初始化方法,由于Servlet是单例,因此整个系统启动时,只会运行一次。
getServletConfig() : 获取Servlet配置信息,也就是以前所说的context-param配置的值。
service() : 监听并响应客户端的请求
getServletInfo() : 获取Servlet信息
destroy() : Servlet容器调用,用于销毁Servlet.
因此,Servlet生命周期分为三个阶段:
1.初始化阶段,调用init()方法
2.响应客户请求阶段,调用service()方法
3.终止阶段,调用destroy()方法
了解了这些Servlet的相关信息,我相信下面再来分析Spring MVC你们就会清楚不少。
三、Spring MVC父子容器及初始化组件
在Spring中咱们都知道,它的核心概念是bean。而Spring容器又是经过BeanFactory来管理bean的。当咱们查看Spring的BeanFactory的体系结构的时候不难发现HierarchicalBeanFactory这个接口。
public interface HierarchicalBeanFactory extends BeanFactory {
BeanFactory getParentBeanFactory();
boolean containsLocalBean(String name);`
}
复制代码
能够看到它有一个getParentBeanFactory()方法。那么Spring框架就能够创建起.器的结构.在使用Spring MVC的时候咱们能够看出,Spring MVC的体系是基于Spring容器来的。下面咱们就来看一下Spring MVC是如何构建起父子容器的。在此以前咱们先来看一段web.xml配置文件。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- init root webapplicationcontext -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- init servlet webapplicationcontext -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
复制代码
相信你们对于以上配置文件不会陌生,以咱们以前的Servlet容器的初始化顺序咱们来看一下以上配置文件。
首先,把contextConfigLocation这个参数以及它的值初始化到ServletContext中。
而后,初始化ContextLoaderListener加载contextConfigLocation里面配置的Spring配置文件,构建起root容器
最后,初始化DispatcherServlet加载它里面的contextConfigLocation,构造起web容器。再把root容器与web容器创建起父子关系。
下面咱们以源代码的形式来讲明以上的过程:
首先,咱们先来看一下ContextLoaderListener类结构。
contextInitialized() : 容器初始化的时候调用。
contextDestroyed() : 容器销毁的时候调用。
因此在Servlet容器初始化的时候会调用contextInitialized方法。
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
try {
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
if (cwac.getParent() == null) {
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
}
return this.context;
}
}
复制代码
3.1 经过反射建立root容器对象
在最开始它会经过反射的方式调用createWebApplicationContext()建立默认的配置在ContextLoader.properties里面的WebApplicationContext接口实例XmlWebApplicationContext。
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
// 检测ContextClass
Class<?> contextClass = determineContextClass(sc);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
复制代码
由于没有配置contextClass因此会加载配置在ContextLoader.properties里面的对象。
protected Class<?> determineContextClass(ServletContext servletContext) {
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
if (contextClassName != null) {
try {
return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class [" + contextClassName + "]", ex);
}
}
else {
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try {
return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName + "]", ex);
}
}
}
复制代码
3.2 加载相应配置文件,初始化root容器
而后调用configureAndRefreshWebApplicationContext方法获取到配置在web.xml里面的configLocationParam值。把它配置成Spring容器的资源位置,最后经过调用wac.refresh()对于整个Spring容器进行加载。
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) { if (ObjectUtils.identityToString(wac).equals(wac.getId())) { String idParam = sc.getInitParameter(CONTEXT_ID_PARAM); if (idParam != null) { wac.setId(idParam); } else { wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(sc.getContextPath())); } }
wac.setServletContext(sc);
// 获取contextConfigLocation值
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
// 加载并刷新Spring容器
wac.refresh();
}
复制代码
3.3 把root容器放在ServletContext中
把初始化好的root 容器以WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE为key,放在Servlet容器当中,以备后面使用。
3.4 关联Servlet WebApplicationContext与 Root WebApplicationContext
咱们知道servlet的规范中,servlet装载时会调用其init()方法,那么天然是调用DispatcherServlet的init方法,经过源码一看,居然没有,可是并不带表真的没有,你会发如今父类的父类中:org.springframework.web.servlet.HttpServletBean有这个方法,以下图所示:
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}
// 把DispatcherServlet里面的init-param转化成PropertyValues
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
// 把DispatcherServlet转换成BeanWrapper,这样就把DispatcherServlet转换成了Spring中的Bean管理
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");
}
}
复制代码
注意代码:initServletBean(); 其他的都和加载bean关系并非特别大,跟踪进去会发I发现这个方法是在类:org.springframework.web.servlet.FrameworkServlet类中(是DispatcherServlet的父类、HttpServletBean的子类),内部经过调用initWebApplicationContext()来初始化一个WebApplicationContext,源码片断(篇幅所限,不拷贝全部源码,仅仅截取片断)
// 获取到root 容器
protected WebApplicationContext initWebApplicationContext() {
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
if (cwac.getParent() == null) {
// 设置父容器
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
wac = findWebApplicationContext();
}
if (wac == null) {
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
onRefresh(wac);
}
if (this.publishContext) {
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
复制代码
最后调用configureAndRefreshWebApplicationContext方法获取到DispatcherServlet里面的contextConfigLocation值,建立并这个Servlet WebApplicationContex.
3.5 初始化Spring MVC默认组件
DispatcherServlet的初始化主线的执行体系是顺着其继承结构依次进行的,咱们在以前曾经讨论过它的执行次序。因此,只有在FrameworkServlet完成了对于WebApplicationContext和组件的初始化以后,执行权才被正式转移到DispatcherServlet中。咱们能够来看看DispatcherServlet此时究竟干了哪些事:
/**
* This implementation calls {@link #initStrategies}.
*/
@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
/**
* Initialize the strategy objects that this servlet uses.
* <p>May be overridden in subclasses in order to initialize further strategy objects.
*/
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
复制代码
onRefresh是FrameworkServlet中预留的扩展方法,在DispatcherServlet中作了一个基本实现:initStrategies。咱们粗略一看,很容易就能明白DispatcherServlet到底在这里干些什么了:初始化组件。
读者或许会问,组件不是已经在WebApplicationContext初始化的时候已经被初始化过了嘛?这里所谓的组件初始化,指的又是什么呢?让咱们来看看其中的一个方法的源码:
/**
* Initialize the MultipartResolver used by this class.
* <p>If no bean is defined with the given name in the BeanFactory for this namespace,
* no multipart handling is provided.
*/
private void initMultipartResolver(ApplicationContext context) {
try {
this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");
}
} catch (NoSuchBeanDefinitionException ex) {
// Default is no multipart resolver.
this.multipartResolver = null;
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate MultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME +
"': no multipart request handling provided");
}
}
}
复制代码
原来,这里的初始化,指的是DispatcherServlet从容器(WebApplicationContext)中读取组件的实现类,并缓存于DispatcherServlet内部的过程。还记得咱们以前给出的DispatcherServlet的数据结构吗?这些位于DispatcherServlet内部的组件实际上只是一些来源于容器缓存实例,不过它们一样也是DispatcherServlet进行后续操做的基础。
到了这里,把Spring MVC与Servlet容器的关系,以及Spring MVC经过Servlet容器的初始化顺序建立父子容器,以及根据Servlet的生命周期的init()方法来初始化Spring MVC的默认组件展示了出来。
四、Spring MVC的处理HTTP请求 Spring MVC要处理http请求,它首先要解决3个问题。
URL到框架的映射。
http请求参数绑定
http响应的生成和输出
4.1 URL到框架的映射
在Spring MVC咱们只须要建立一个对象在上面标注@Controller注解。而后建立一个方法标注@RequestMapping而后这个方法就可以处理对应的url了。具体解析能够参看 – Spring MVC @RequestMapping
4.2 http请求参数绑定
对于http请求参数的绑定,在Spring MVC生成URL到框架的映射关系时会建立一个HandlerMethod对象。这个对象里面包括了这个url对应Spring对应标注了@RequestMapping方法的MethodParameter(方法参数)。经过HttpServletRequest获取到请求参数,而后再经过HandlerMethodArgumentResolver接口把请求参数绑定到方法参数中。
public interface HandlerMethodArgumentResolver {
boolean supportsParameter(MethodParameter parameter);
Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception;
}
复制代码
具体能够参考 – Spring MVC DataBinder
4.3 http响应的生成和输出
在整个系统运行的过程当中处于Servlet的service()方法都处于侦听模式,侦听并处理全部的Web请求。所以,在service及其相关方法中,咱们看到的则是对Http请求的处理流程。
在Spring MVC容器在初始的时候建立了URL到框架的映射,当前端请求的到来的时候。Spring MVC会获取到对应的HandlerMethod对象,HandlerMethod包括里面的属性。
public class HandlerMethod {
/** Logger that is available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
private final Object bean;
private final BeanFactory beanFactory;
private final Class<?> beanType;
private final Method method;
private final Method bridgedMethod;
private final MethodParameter[] parameters;
private HttpStatus responseStatus;
private String responseStatusReason;
private HandlerMethod resolvedFromHandlerMethod;
}
复制代码
其中最主要的属性是如下三个:
bean : @Controller对象实例。
method :@Controller对象实例标注了@RequestMapping的方法对象,也就是处理对应url的方法
parameters : @RequestMapping里面的方法参数。
经过http请求参数绑定,把Request请求的参数绑定解析成对应的方法参数。而后经过反射:
method.invoke(bean, paramters);
复制代码
完成对http请求的整个响应。 具体能够参见 – Spring MVC DispatcherServlet
为何某些人会一直比你优秀,是由于他自己就很优秀还一直在持续努力变得更优秀,而你是否是还在知足于现状心里在窃喜!
合理利用本身每一分每一秒的时间来学习提高本身,不要再用"没有时间“来掩饰本身思想上的懒惰!趁年轻,使劲拼,给将来的本身一个交代!
To-陌霖Java架构
分享互联网最新文章 关注互联网最新发展