分析spring webmvc启动流程:serlvet注册、IoC容器创建、bean初始化、MVC的流程
1.Spring和SpringMVC
Spring是一个开源容器框架,可以接管web层,业务层,dao层,持久层的组件,并且可以配置各种bean,和维护bean与bean之间的关系。其核心就是控制反转(IOC),和面向切面(AOP),简单的说就是一个分层的轻量级开源框架。
Spring为简化我们的开发工作,封装了一系列的开箱即用的组件功能模块,包括:Spring JDBC 、Spring MVC 、Spring Security、 Spring AOP 、Spring ORM 、Spring Test等。
IOC的本质就是把bean的管理交给框架去做,spring自己维护一个bean容器,将所有bean进行统一管理,这样一来,所有需要用到实例的场景都不需要写繁琐且重复的实例化代码,而是简单地完成bean声明和注入依赖就可以了。
AOP的本质是利用动态代理完成统一切面的功能,利用AOP,我们可以把一些横向的同一类型代码进行复用,比如登录拦截,身份校验,安全管理等等,这些不需要内嵌到业务代码中,但却经常要用到的东西,就可以利用AOP来做成一个切面,然后指定需要拦截的方法,AOP通过动态代理会将切面代码加入到代理对象中,于是你执行业务代码时,相当于在执行代理对象,就会相应地调用切面方法。
SpringMVC是属于SpringWeb里面的一个功能模块(SpringWebMVC)。专门用来开发SpringWeb项目的一种MVC模式的技术框架实现。
- model层,负责提供数据模型,以及和数据库进行交互
- controller层,负责分发和处理web请求,这里指的是HTTP请求,一般的controller会处理对应url的web请求
-
view层渲染页面并返回需要的对象类型,例如json,html等等
2.SpringMVC的工作原理
1、用户发送请求至前端控制器DispatcherServlet。
2、DispatcherServlet收到请求调用HandlerMapping处理器映射器。
3、处理器映射器找到具体的处理器(可以根据xml配置、注解进行查找),生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
4、 DispatcherServlet调用HandlerAdapter处理器适配器。
5、HandlerAdapter经过适配调用具体的处理器(Controller,也叫后端控制器)。
6、Controller执行完成返回ModelAndView。
7、HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet。
8、DispatcherServlet将ModelAndView传给ViewReslover视图解析器。
9、ViewReslover解析后返回具体View.
10、DispatcherServlet根据View进行渲染视图(即将模型数据填充至视图中)。
11、DispatcherServlet响应用户。
3.springMVC配置
web.xml配置
使用contextConfigLocation参数来加载springMVC的配置文件
<servlet>
<servlet-name>springMBV</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springmvc.xml</param-value>
</init-param>
</servlet>
匹配对应url类型的mapping
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
定义环境变量
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
定义listener监听器
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
在使用contextConfigLocation所定义的配置文件,springmvc.xml中配置处理器映射器Handler(controller)
<bean id="bean" class="bean.TestBean" />
也可以直接配置URL处理器映射器
<!-- 简单URL配置处理器映射器 -->
<bean id="url1" class="bean.url1" />
<bean id="url2" class="bean.url2" />
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/url1">url1</prop>
<prop key="/url2">url2</prop>
</props>
</property>
</bean>
实现Controller
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
Handler实现
在对应的Handler类中实现Controller接口
public class HelloController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView modelView = new ModelAndView();
modelView.setViewName("/WEB-INF/jsp/index.jsp");
return modelView;
}
}
或者实现HttpRequestHandler接口
public class HelloController2 implements HttpRequestHandler {
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("name", "abc");
request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);
}
}
view配置
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" />
其他方法
批量配置,自动扫描
<context:component-scan base-package="com.java.code"/>
使用注解
@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解。
使用@Controller 注解,在对应的方法上,视图解析器可以解析return 的jsp,html页面,并且跳转到相应页面;
@org.springframework.stereotype.Controller
public class Controller {
}
使用@RequestMapping 注解映射请求路径
一般来说,类级别的注解负责将一个特定(或符合某种模式)的请求路径映射到一个控制器上,同时通过方法级别的注解来细化映射,即根据特定的HTTP请求方法(GET、POST 方法等)、HTTP请求中是否携带特定参数等条件,将请求映射到匹配的方法上
@RequestMapping(path = "showHomework",method = RequestMethod.GET)
public ModelAndView showHomework(){
List<Homework> list = new StudentHomeworkJdbc().findAll();
return new ModelAndView("showHomework.jsp","list",list);
}
Controller的返回类型
- ModelAndView
- Model
- ModelMap
- Map
- View
- String
- Void
5.启动流程
根据Servlet的文档可知一个Web应用被部署到容器中(Tomcat为例),在开始接受相应之前,会执行以下步骤
- 部署描述文件中(eg.tomcat的web.xml)由<listener>元素标记的事件监听器会被创建和初始化
- 对于所有事件监听器,如果实现了ServletContextListener接口,将会执行其实现的contextInitialized()方法
- 部署描述文件中由<filter>元素标记的过滤器会被创建和初始化,并调用其init()方法
- 部署描述文件中由<servlet>元素标记的servlet会根据<load-on-startup>的权值按顺序创建和初始化,并调用其init()方法
Listener初始化
在springMVC中,先会初始化由<context-param>定义的全局变量
接着定义一个ContextLoaderListener类继承了ContextLoader类并实现了ServletContextListener接口,并重写contextInitialized方法
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
ContextLoaderListener的contextInitialized()方法直接调用了initWebApplicationContext()方法,这个方法是继承自ContextLoader类,通过函数名可以知道,该方法是用于初始化Web应用上下文,即IoC容器,继续查看ContextLoader类的initWebApplicationContext()方法的源码如下:
/**
* Initialize Spring's web application context for the given servlet context,
* using the application context provided at construction time, or creating a new one
* according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
* "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
* @param servletContext current servlet context
* @return the new WebApplicationContext
* @see #ContextLoader(WebApplicationContext)
* @see #CONTEXT_CLASS_PARAM
* @see #CONFIG_LOCATION_PARAM
*/
//servletContext,servlet上下文,即application对象
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
/*
首先通过WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
这个String类型的静态变量获取一个根IoC容器,根IoC容器作为全局变量
存储在application对象中,如果存在则有且只能有一个
如果在初始化根WebApplicationContext即根IoC容器时发现已经存在
则直接抛出异常,因此web.xml中只允许存在一个ContextLoader类或其子类的对象
*/
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
}
Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring root WebApplicationContext");
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();
try {
// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
// 如果当前成员变量中不存在WebApplicationContext则创建一个根WebApplicationContext
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent ->
// determine parent for root web application context, if any.
//为根WebApplicationContext设置一个父容器
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
//配置并刷新整个根IoC容器,在这里会进行Bean的创建和初始化
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
/*
将创建好的IoC容器放入到application对象中,并设置key为WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
因此,在SpringMVC开发中可以在jsp中通过该key在application对象中获取到根IoC容器,进而获取到相应的Ben
*/
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);
}
if (logger.isDebugEnabled()) {
logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
}
return this.context;
}
catch (RuntimeException ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
catch (Error err) {
logger.error("Context initialization failed", err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
throw err;
}
}
initWebApplicationContext()方法创建了root WebApplicationContext对象,即根IoC容器。 且IoC容器有且只能有一个,根IoC容器作为全局变量存储在ServletContext即application对象中。将根IoC容器放入到application对象之前进行了IoC容器的配置和刷新操作,调用了configureAndRefreshWebApplicationContext()方法,该方法源码如下:
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
wac.setServletContext(sc);
/*
CONFIG_LOCATION_PARAM = "contextConfigLocation"
获取web.xml中<context-param>标签配置的全局变量,其中key为CONFIG_LOCATION_PARAM
也就是我们配置的相应Bean的xml文件名,并将其放入到WebApplicationContext中
*/
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
wac.refresh();
}
获取到了web.xml中的<context-param>标签配置的全局变量contextConfigLocation,并最后一行调用了refresh()方法,ConfigurableWebApplicationContext是一个接口,通过对常用实现类ClassPathXmlApplicationContext逐层查找后可以找到一个抽象类AbstractApplicationContext实现了refresh()方法,其源码如下:
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
该方法主要用于创建并初始化contextConfigLocation类配置的xml文件中的Bean,因此,如果我们在配置Bean时出错,在Web应用启动时就会抛出异常,而不是等到运行时才抛出异常。
整个ContextLoaderListener类的启动过程到此就结束了,可以发现,创建ContextLoaderListener是比较核心的一个步骤,主要工作就是为了创建根IoC容器并使用特定的key将其放入到application对象中,供整个Web应用使用,由于在ContextLoaderListener类中构造的根IoC容器配置的Bean是全局共享的,因此,在<context-param>标识的contextConfigLocation的xml配置文件一般包括:数据库DataSource、DAO层、Service层、事务等相关Bean。
Servlet注册
Web应用启动的最后一个步骤就是创建和初始化相关Servlet,在开发中常用的Servlet就是DispatcherServlet类前端控制器。
DispatcherServelt类的本质是Servlet,在Web应用部署到容器后进行Servlet初始化时会调用相关的init(ServletConfig)方法,因此,DispatchServlet类的初始化过程也由该方法开始。上述调用逻辑中比较重要的就是FrameworkServlet抽象类中的initServletBean()方法、initWebApplicationContext()方法以及DispatcherServlet类中的onRefresh()方法。HttpServletBean抽象类在执行init()方法时会调用initServletBean()方法,由于多态的特性,最终会调用其子类FrameworkServlet抽象类的initServletBean()方法。该方法由final标识,子类就不可再次重写了。该方法中比较重要的就是initWebApplicationContext()方法的调用,该方法仍由FrameworkServlet抽象类实现,继续查看其源码如下所示:
/**
* Initialize and publish the WebApplicationContext for this servlet.
* <p>Delegates to {@link #createWebApplicationContext} for actual creation
* of the context. Can be overridden in subclasses.
* @return the WebApplicationContext instance
* @see #FrameworkServlet(WebApplicationContext)
* @see #setContextClass
* @see #setContextConfigLocation
*/
protected WebApplicationContext initWebApplicationContext() {
/*
获取由ContextLoaderListener创建的根IoC容器
获取根IoC容器有两种方法,还可通过key直接获取
*/
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent
/*
如果当前Servelt存在一个WebApplicationContext即子IoC容器
并且上文获取的根IoC容器存在,则将根IoC容器作为子IoC容器的父容器
*/
cwac.setParent(rootContext);
}
//配置并刷新当前的子IoC容器,功能与前文讲解根IoC容器时的配置刷新一致,用于构建相关Bean
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
//如果当前Servlet不存在一个子IoC容器则去查找一下
wac = findWebApplicationContext();
}
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
//如果仍旧没有查找到子IoC容器则创建一个子IoC容器
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
//调用子类覆盖的onRefresh方法完成“可变”的初始化过程
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
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;
}
该方法的主要作用同样是创建一个WebApplicationContext对象,即Ioc容器,不过前文讲过每个Web应用最多只能存在一个根IoC容器,这里创建的则是特定Servlet拥有的子IoC容器。子容器中管理的Bean一般只被该Servlet使用,因此,其中管理的Bean一般是“局部”的。
当IoC子容器构造完成后调用了onRefresh()方法,该方法的调用与initServletBean()方法的调用相同,由父类调用但具体实现由子类覆盖,调用onRefresh()方法时将前文创建的IoC子容器作为参数传入,查看DispatcherServletBean类的onRefresh()方法源码如下:
/**
* This implementation calls {@link #initStrategies}.
*/
//context为DispatcherServlet创建的一个IoC子容器
@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);
}
总的来说DispatchServlet初始化的过程:
HttpServletBean.init()-->FrameworkServlet.initServletBean()-->FrameworkServlet.initWebApplicationContext()-->DispatcherServlet.onRefresh(ApplicationContext context)
至此Servlet注册完成