- 首先简单理解Spring容器和SpringMVC的关系
- web.xml中spring的核心ContextLoaderListener初始化的上下文和springmvc的核心DispatcherServlet初始化的上下文关系:
- Spring容器和SpringMVC容器虽然是父容器与子容器的关系,但二者之间具有一定的独立性。具体来说,两个容器基于各自的配置文件分别进行初始化,只有在子容器找不到对应的Bean时,才回去父容器中去找并加载。
-
此外,一般地,SpringMVC容器只管理Controller,剩下的Service、Repository 和 Component 由Spring容器去管理,不建议两个容器上在管理Bean上发生交叉。
- web.xml中spring的核心ContextLoaderListener初始化的上下文和springmvc的核心DispatcherServlet初始化的上下文关系:
2. 环境搭建
工程目录如下:
然后就是部署Tomcat的web运行环境,注意web.xml,applicationContext.xml,spring-mvc.xml中关于路径的配置都是相对于classpath或WEB-INF配置的,因为实际生产环境中可能只有项目运行代码,并没有源文件,运行时需要到web项目下加载文件。
-
-
-
- web.xml
View Code
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_4_0.xsd" 5 version="4.0"> 6 7 <welcome-file-list> 8 <welcome-file>index.jsp</welcome-file> 9 </welcome-file-list> 10 11 <!-- 用于加载Spring --> 12 <listener> 13 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 14 </listener> 15 <listener> 16 <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> 17 </listener> 18 19 <!-- 配置applicationContext.xml文件位置 --> 20 <context-param> 21 <param-name>contextConfigLocation</param-name> 22 <param-value>classpath:config/spring/applicationContext.xml</param-value> 23 </context-param> 24 25 <!-- 加载log4j2 --> 26 <listener> 27 <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class> 28 </listener> 29 30 <!-- 配置log4j2.xml文件位置 --> 31 <context-param> 32 <param-name>log4jConfiguration</param-name> 33 <param-value>classpath:config/log/log4j2.xml</param-value> 34 </context-param> 35 36 <filter> 37 <filter-name>encodingFilter</filter-name> 38 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 39 <init-param> 40 <param-name>encoding</param-name> 41 <param-value>UTF-8</param-value> 42 </init-param> 43 <init-param> 44 <param-name>forceEncoding</param-name> 45 <param-value>true</param-value> 46 </init-param> 47 </filter> 48 <filter-mapping> 49 <filter-name>encodingFilter</filter-name> 50 <url-pattern>/*</url-pattern> 51 </filter-mapping> 52 53 <!-- 前端控制器配置 --> 54 <servlet> 55 <servlet-name>dispatcher</servlet-name> 56 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 57 <init-param> 58 <param-name>contextConfigLocation</param-name> 59 <param-value>classpath:config/spring/spring-mvc.xml</param-value> 60 </init-param> 61 <load-on-startup>1</load-on-startup> 62 </servlet> 63 <servlet-mapping> 64 <servlet-name>dispatcher</servlet-name> 65 <url-pattern>/</url-pattern> 66 </servlet-mapping> 67 68 <!-- 配置session过期时间(以分为单位) --> 69 <session-config> 70 <session-timeout>30</session-timeout> 71 </session-config> 72 </web-app>
- web.xml
-
-