spring web项目启动入口

1、首先看一下传统Java Web的配置文件web.xml,网上找的一个,参考地址:https://blog.csdn.net/github_36301064/article/details/53290900

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  5. version="3.1">
  6.  
  7. <servlet>
  8. <servlet-name>default</servlet-name>
  9. <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
  10. <init-param>
  11. <param-name>debug</param-name>
  12. <param-value>0</param-value>
  13. </init-param>
  14. <init-param>
  15. <param-name>listings</param-name>
  16. <param-value>false</param-value>
  17. </init-param>
  18. <load-on-startup>1</load-on-startup>
  19. </servlet>
  20.  
  21. <servlet>
  22. <servlet-name>jsp</servlet-name>
  23. <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
  24. <init-param>
  25. <param-name>fork</param-name>
  26. <param-value>false</param-value>
  27. </init-param>
  28. <init-param>
  29. <param-name>xpoweredBy</param-name>
  30. <param-value>false</param-value>
  31. </init-param>
  32. <load-on-startup>3</load-on-startup>
  33. </servlet>
  34.  
  35. <servlet-mapping>
  36. <servlet-name>default</servlet-name>
  37. <url-pattern>/</url-pattern>
  38. </servlet-mapping>
  39.  
  40. <servlet-mapping>
  41. <servlet-name>jsp</servlet-name>
  42. <url-pattern>*.jsp</url-pattern>
  43. <url-pattern>*.jspx</url-pattern>
  44. </servlet-mapping>
  45.  
  46. <session-config>
  47. <session-timeout>30</session-timeout>
  48. </session-config>
  49.  
  50. <!-- 这里省略了大概4000多行的MIME类型的定义,这里只给出两种MIME类型的定义 -->
  51. <mime-mapping>
  52. <extension>bmp</extension>
  53. <mime-type>image/bmp</mime-type>
  54. </mime-mapping>
  55. <mime-mapping>
  56. <extension>htm</extension>
  57. <mime-type>text/html</mime-type>
  58. </mime-mapping>
  59.  
  60. <welcome-file-list>
  61. <welcome-file>index.html</welcome-file>
  62. <welcome-file>index.htm</welcome-file>
  63. <welcome-file>index.jsp</welcome-file>
  64. </welcome-file-list>
  65. </web-app>

2、看一下spring web项目中的web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  5. version="3.1">
  6.  
  7. <context-param>
  8. <param-name>contextConfigLocation</param-name>
  9. <param-value>/WEB-INF/applicationContext.xml</param-value>
  10. </context-param>
  11. <listener>
  12. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  13. </listener>
  14. <servlet>
  15. <servlet-name>dispatcher</servlet-name>
  16. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  17. <init-param>
  18. <param-name>contextConfigLocation</param-name>
  19. <param-value>/WEB-INF/dispatcher-servlet2.xml</param-value>
  20. </init-param>
  21. <load-on-startup>1</load-on-startup>
  22. </servlet>
  23. <servlet-mapping>
  24. <servlet-name>dispatcher</servlet-name>
  25. <url-pattern>/</url-pattern>
  26. </servlet-mapping>
  27. <welcome-file-list>
  28. <welcome-file>index.jsp</welcome-file>
  29. </welcome-file-list>
  30.  
  31. <filter>
  32. <filter-name>CharacterEncodingFilter</filter-name>
  33. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  34. <init-param>
  35. <param-name>encoding</param-name>
  36. <param-value>utf-8</param-value>
  37. </init-param>
  38. </filter>
  39. <filter-mapping>
  40. <filter-name>CharacterEncodingFilter</filter-name>
  41. <url-pattern>/*</url-pattern>
  42. </filter-mapping>
  43. </web-app>

dispatcher对应的servlet下的init-param可以不设置,默认使用/WEB-INF/dispatcher-servlet.xml

3、Tomcat等web容器启动干了什么,参考:https://blog.csdn.net/lieyanhaipo/article/details/58605545

容器启动的时候会调用 listen-class 的初始化事件,即 org.springframework.web.context.ContextLoaderListener 的初始化方法会被调用,同时 org.springframework.web.context.ContextLoaderListener 必须实现javax.servlet.ServletContextListener(Servlet)接口,

public void contextInitialized(ServletContextEvent sce); 接口中的初始化方法会被调用

  1. public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
  2.  
  3. public ContextLoaderListener() {
  4. }
  5.  
  6. public ContextLoaderListener(WebApplicationContext context) {
  7. super(context);
  8. }
  9.  
  10. @Override
  11. public void contextInitialized(ServletContextEvent event) {
  12. initWebApplicationContext(event.getServletContext());
  13. }
  14.  
  15. @Override
  16. public void contextDestroyed(ServletContextEvent event) {
  17. closeWebApplicationContext(event.getServletContext());
  18. ContextCleanupListener.cleanupAttributes(event.getServletContext());
  19. }
  20.  
  21. }

具体的实现在父类ContextLoader中

  1. public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
  2. if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
  3. throw new IllegalStateException(
  4. "Cannot initialize context because there is already a root application context present - " +
  5. "check whether you have multiple ContextLoader* definitions in your web.xml!");
  6. }
  7.  
  8. Log logger = LogFactory.getLog(ContextLoader.class);
  9. servletContext.log("Initializing Spring root WebApplicationContext");
  10. if (logger.isInfoEnabled()) {
  11. logger.info("Root WebApplicationContext: initialization started");// spring web启动日志
  12. }
  13. long startTime = System.currentTimeMillis();
  14.  
  15. try {
  16. // Store context in local instance variable, to guarantee that
  17. // it is available on ServletContext shutdown.
  18. if (this.context == null) {
  19. this.context = createWebApplicationContext(servletContext);// 创建WebApplicationContext,默认WebApplicationContext为XmlWebApplicationContext
  20. }
  21. if (this.context instanceof ConfigurableWebApplicationContext) {
  22. ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
  23. if (!cwac.isActive()) {
  24. // The context has not yet been refreshed -> provide services such as
  25. // setting the parent context, setting the application context id, etc
  26. if (cwac.getParent() == null) {
  27. // The context instance was injected without an explicit parent ->
  28. // determine parent for root web application context, if any.
  29. ApplicationContext parent = loadParentContext(servletContext);
  30. cwac.setParent(parent);
  31. }
  32. configureAndRefreshWebApplicationContext(cwac, servletContext);
  33. }
  34. }
  35. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
  36.  
  37. ClassLoader ccl = Thread.currentThread().getContextClassLoader();
  38. if (ccl == ContextLoader.class.getClassLoader()) {
  39. currentContext = this.context;
  40. }
  41. else if (ccl != null) {
  42. currentContextPerThread.put(ccl, this.context);
  43. }
  44.  
  45. if (logger.isDebugEnabled()) {
  46. logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
  47. WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
  48. }
  49. if (logger.isInfoEnabled()) {
  50. long elapsedTime = System.currentTimeMillis() - startTime;
  51. logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");// spring web启动日志
  52. }
  53.  
  54. return this.context;
  55. }
  56. catch (RuntimeException ex) {
  57. logger.error("Context initialization failed", ex);
  58. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
  59. throw ex;
  60. }
  61. catch (Error err) {
  62. logger.error("Context initialization failed", err);
  63. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
  64. throw err;
  65. }
  66. }

创建上下文代码

  1. protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
  2. Class<?> contextClass = determineContextClass(sc);
  3. if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
  4. throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
  5. "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
  6. }
  7. return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
  8. }
  9.  
  10. /**
  11. * Return the WebApplicationContext implementation class to use, either the
  12. * default XmlWebApplicationContext or a custom context class if specified.
  13. * @param servletContext current servlet context
  14. * @return the WebApplicationContext implementation class to use
  15. * @see #CONTEXT_CLASS_PARAM
  16. * @see org.springframework.web.context.support.XmlWebApplicationContext
  17. */
  18. protected Class<?> determineContextClass(ServletContext servletContext) {
  19. String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);// null
  20. if (contextClassName != null) {
  21. try {
  22. return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
  23. }
  24. catch (ClassNotFoundException ex) {
  25. throw new ApplicationContextException(
  26. "Failed to load custom context class [" + contextClassName + "]", ex);
  27. }
  28. }
  29. else {
  30. contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
  31. try {
  32. return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
  33. }
  34. catch (ClassNotFoundException ex) {
  35. throw new ApplicationContextException(
  36. "Failed to load default context class [" + contextClassName + "]", ex);
  37. }
  38. }
  39. }

spring-web工程下,resource资源目录下

ContextLoader.properties

  1. # Default WebApplicationContext implementation class for ContextLoader.
  2. # Used as fallback when no explicit context implementation has been specified as context-param.
  3. # Not meant to be customized by application developers.
  4.  
  5. org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

默认的WebApplicationContext为XmlWebApplicationContext

  1. private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader.properties";
  2.  
  3. private static final Properties defaultStrategies;
  4.  
  5. static {
  6. // Load default strategy implementations from properties file.
  7. // This is currently strictly internal and not meant to be customized
  8. // by application developers.
  9. try {
  10. ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
  11. defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
  12. }
  13. catch (IOException ex) {
  14. throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
  15. }
  16. }

到此为止,WebApplicationContext(XmlWebApplicationContext)创建完毕。

Java笔记Spring(四)的更多相关文章

  1. Java笔记Spring(七)

    DispatcherServlet初始化,继续分析日志 主要部分: 23-May-2018 17:47:55.457 INFO [RMI TCP Connection(3)-127.0.0.1] or ...

  2. Java笔记Spring(五)

    C:\apache-tomcat-8.0.36\bin\catalina.bat run [2018-05-23 02:30:31,657] Artifact demo-springmvc:war e ...

  3. Java笔记(四)常用基础类

    常用基础类 一)String String内部用一个字符数组表示字符串: private final char value[]; 注意:Java9对此做了优化,采用byte[],如果字符都是ASCII ...

  4. Java笔记Spring(一)

    一.Spring框架 源码地址:https://github.com/spring-projects/spring-framework 构建工具:Gradle,Gradle教程:https://www ...

  5. 菜鸡的Java笔记 第四 - java 基础运算符

    数学运算符,逻辑运算,三目运算,位运算 double d2 = 314e2; //采用科学计数法的写法,表示10的2次方.= 31400.0 代码写的越简单越好   简化运算符 代码:x=x+y 可以 ...

  6. Effective java笔记(四),泛型

    泛型为集合提供了编译时类型检查. 23.不要在代码中使用原生态类型 声明中具有一个或多个类型参数的类或接口统称为泛型.List<E>是一个参数化类,表示元素类型为E的列表.为了提供兼容性, ...

  7. Java笔记(十四)……抽象类与接口

    抽象类概念 抽象定义: 抽象就是从多个事物中将共性的,本质的内容抽取出来. 例如:狼和狗共性都是犬科,犬科就是抽象出来的概念. 抽象类: Java中可以定义没有方法体的方法,该方法的具体实现由子类完成 ...

  8. Java笔记Spring(八)

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  9. Java笔记Spring(六)

    web.xml各节点加载顺序 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns=&q ...

随机推荐

  1. Nginx的使用(二)Nginx配置wordpress

    安装php:https://windows.php.net/download/,php默认启动命令:php-cgi.exe -b 127.0.0.1:9000 安装wordpress:https:// ...

  2. 聚合函数count()

    2018-08-12

  3. JS 中的广度与深度优先遍历

    现在有一种类似树的数据结构,但是不存在共同的根节点 root,每一个节点的结构为 {key: 'one', value: '1', children: [...]},都包含 key 和 value,如 ...

  4. vue 和react的区别

    1.数据是不是可变的 react整体是函数式的思想,把组件设计成纯组件,状态和逻辑通过参数传入,所以在react中,是单向数据流,推崇结合immutable来实现数据不可变. react在setSta ...

  5. List集合2-LinkedList

    一.LinkedList集合 LinkedList集合也是List接口的实现类(没有ArrayList集合常见) 二.LinkedList集合的特点 LinkedList内部是一个链表(双向链表) L ...

  6. github的优势

    1.GitHub作为托管平台只支持git版本库托管而不像其他开源项目托管平台还对CVS.SVN.Hg 等格式的版本库进行托管.GitHub 的哲学很简单,既然 Git 是最好的版本控制系统之一(对于很 ...

  7. SQL-43 将所有to_date为9999-01-01的全部更新为NULL,且 from_date更新为2001-01-01。

    题目描述 将所有to_date为9999-01-01的全部更新为NULL,且 from_date更新为2001-01-01.CREATE TABLE IF NOT EXISTS titles_test ...

  8. Android:layout属性大全

    Android layout属性大全 第一类:属性值 true或者 false android:layout_centerHrizontal 水平居中android:layout_centerVert ...

  9. java基础(3)java常用API

    1 ArrayList集合 01 创建 import java.util.ArrayList; /* 泛型:装在集合中的元素,全都是统一的一种类型.泛型必须是引用类型,不能是基本数据类型 */ pub ...

  10. 关于LaTeX公式排版

    [转载请注明出处]http://www.cnblogs.com/mashiqi 2017/10/05 1.居中括号框住多行公式 \begin{equation*} \left\{\begin{alig ...