之前搭建web项目都是上网搜索资料,配置都是复制的,因为不清楚配置的参数具体作用,通常会遇到不少问题。现在做一下记录,加强理解。
web.xml篇
web.xml文件是用来应用初始化配置信息的。通常我们配置如下两个配置。
<!-- 配置spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/application*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
ContextLoaderListener的作用可以通过源码来分析
public class ContextLoaderListener extends ContextLoader implements ServletContextListener
可以看到它继承了ContextLoader,ContextLoader主要有两个方法initWebApplicationContext和closeWebApplicationContext,简单讲就是Spring托管Bean的IOC容器初始化和关闭的方法。我们可以通过ContextLoaderListener来监听执行IOC容器初始化和关闭的方法。
那么何时才会执行这两个方法?
可以看到ContextLoaderListener也实现了ServletContextListener。在服务器启动时ServletContext会被创建,而同时调用上下文初始化工作。
好了,listener的作用我们大概知道了。
上文中提到的另外一个配置context-param这个的作用是什么?可以试想一下,如果我们想自己写的类给Spring托管,应用是如何知道的?context-param的作用就是告诉ContextLoaderListener读取在contextConfigLocation中定义的xml文件去加载配置信息的。
当然,搭建SpringMVC也少不了这两个配置。
<!-- 配置SpringMVC核心控制器 -->
<servlet>
<servlet-name>springmvc-web</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc-web</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
SpringMvc是基于servlet封装而成的框架,而DispatcherServlet是SpringMvc的访问点,这里的配置就是初始DispatcherServlet的配置。servlet-mapping就是对请求的拦截, / 拦截的类型是servlet,也就是说servlet请求都会通过DispatcherServlet去分发。(其他拦截类型可自行百度,容易找)
<servlet-mapping>配置为/时,SpringMvc配置文件通常要以下两个配置。具体作用后面有空再写。
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 访问资源的前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".html"></property> </bean>