文章目录
了解springmvc
springmvc官网https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-servlet
springmvc是基于spring的一个web层框架,同样也是web层框架的有struts,struts2等等,但是struts因为漏洞等问题,被慢慢淘汰了,现在基本都在用springmvc;
相信以前面试的时候总是背了springmvc的执行流程:
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响应用户。
虽然背的挺熟,但是没有看过源码,印象总不是很深;因为springmvc基本都有用过,所以有些地方就简述了;
启动流程
首先,我们看一下在web.xml配置的一些东西:
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/config/beans.xml</param-value>
</context-param>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
前面一个是配置spring容器的,后面就是配置springmvc的;DispatcherServlet顾名思义,是一个servlet,先看看DispatcherServlet的类图:
httpServietBean的init方法
关于servlet就不做过多描述了,servlet入口就是init方法,我们从init方法看,先执行genericServlet的init然后genericServlet又是执行子类httpServietBean的init方法:
@Override
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}
// Set bean properties from init parameters.
// 对Servlet初始化参数封装成PropertyValues对象
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
//将serlvet封装为BeanWrapper对象
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
// 资源加载器
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
// 设置一个属性编辑器
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
// 执行init,(留给子类覆盖的,dispatcherServlet都没有覆盖方法,所以是空的)
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.
// 初始化serlvetBean了
initServletBean();
if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
initServletBean方法比较简单:
initWebApplicationContext方法是主要初始化子容器,跟dispatcherservlet的方法:
protected WebApplicationContext initWebApplicationContext() {
//获取web.xml配置的spring容器
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
// web容器,一般开始为空;springboot项目则不为空;
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
cwac.setParent(rootContext);
}
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
wac = findWebApplicationContext();
}
// 根据父容器,创建web容器,就是子容器,这里面子容器进行了刷新
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
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.
// 刷新上下文,这里主要加载dispatcherservlet的组件
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
// 将web容器作为servlet上下文属性进行发布
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;
}
createWebApplicationContext就是创建子容器的主要方法:
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
return createWebApplicationContext((ApplicationContext) parent);
}
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
// 获取web容器的类型
Class<?> contextClass = getContextClass();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Servlet with name '" + getServletName() +
"' will try to create custom WebApplicationContext context of class '" +
contextClass.getName() + "'" + ", using parent context [" + parent + "]");
}
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException(
"Fatal initialization error in servlet with name '" + getServletName() +
"': custom WebApplicationContext class [" + contextClass.getName() +
"] is not of type ConfigurableWebApplicationContext");
}
// 反射创建web容器
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
// 设置环境
wac.setEnvironment(getEnvironment());
// 设置父容器
wac.setParent(parent);
//设置配置文件地址
wac.setConfigLocation(getContextConfigLocation());
// 加载配置,刷新容器
configureAndRefreshWebApplicationContext(wac);
return wac;
}
看一下加载配置和刷新容器的地方:
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
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
if (this.contextId != null) {
wac.setId(this.contextId);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
}
}
// 设置web容器所属的servletcontext
wac.setServletContext(getServletContext());
// 设置servletconfig
wac.setServletConfig(getServletConfig());
// 设置命名空间
wac.setNamespace(getNamespace());
// 设置监听器
wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));
// 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(getServletContext(), getServletConfig());
}
// web容器的钩子方法,跟spring容器的BeanPostProcess差不多
postProcessWebApplicationContext(wac);
// 添加一些初始化器,如果没有设置就没有
applyInitializers(wac);
// 刷新容器就是走的spring容器刷新
wac.refresh();
}
onRefresh刷新dispatcherservlet九大组件的主要地方
onRefresh在frameworkservlet方法里是空的,在dispatcherservlet里重写了onRefresh方法,我们看dispatcherservlet里面的:
@Override
protected void onRefresh(ApplicationContext context) {
//初始化九大组件
initStrategies(context);
}
protected void initStrategies(ApplicationContext context) {
// 初始化文件上传解析器
initMultipartResolver(context);
// 本地化解析
initLocaleResolver(context);
// 主题解析器
initThemeResolver(context);
// 处理器映射器 保存Url映射关系
initHandlerMappings(context);
// 处理器适配器
initHandlerAdapters(context);
// 异常解析器
initHandlerExceptionResolvers(context);
// 视图提取器,从request中获取viemName
initRequestToViewNameTranslator(context);
// 视图解析器
initViewResolvers(context);
// 参数解析器
initFlashMapManager(context);
}