spring和springMVC在web.xml中配置
spring配置:
<!--Spring配置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springcfg/*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
下面是对配置文件的说明
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
ContextLoaderListener是Spring的监听器,它的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springcfg/*.xml</param-value>
</context-param>
这段配置是用于指定applicationContext.xml配置文件的位置,可通过context-param加以指定:这段代码的大致意思就是寻找class文件下的springcfg文件下的所有后缀为.xml的配置文件,同样的,这种方式是同时加载可以配置多个xml的
springMVC配置
<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:springcfg/springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
SpringMVC是一个基于DispatcherServlet的MVC框架,每一个请求最先访问的都是DispatcherServlet,DispatcherServlet负责转发每一个Request请求给相应的Handler,Handler处理以后再返回相应的视图(View)和模型(Model),返回的视图和模型都可以不指定,即可以只返回Model或只返回View或都不返回,并且DispatcherServlet是继承自HttpServlet的,所以在我们的web.xml中,我们是可以用启动servlet方式来启动springmvc的。
而上面的代码中<init-param>标签是可以直接省略掉的,如果没有<init-param>标签,那么spring框架就是默认去找WEB-INF下springmvc-servlet.xml文件
<load-on-startup>标签介绍:
- 元素标记容器是否应该在web应用程序启动的时候就加载这个servlet
- 它的值必须是一个整数,表示servlet被加载的先后顺序
- 如果该元素的值为负数或者没有设置,则容器会当Servlet被请求时再加载
- 如果值为正整数或者0时,表示容器在应用启动时就加载并初始化这个servlet,值越小,servlet的优先级越高,就越先被加载。值相同时,容器就会自己选择顺序来加载
最后总体的spring+springMVC配置文件是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!--加载springMVC-->
<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:springcfg/springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<!--Spring配置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springcfg/springCfg.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
项目地址:
链接:https://pan.baidu.com/s/1VVZHhBRjFJJxeQVNMxWUNQ
提取码:ka53