spring spring mvc集成

来源:互联网 发布:js弹出模态框 编辑:程序博客网 时间:2024/04/30 03:01

本文使用的是spring3.1.0, 主要讲解spring的配置文件默认位置和指定spring配置文件的位置。

1、默认位置

A) 默认spring mvc配置文件
在web.xml文件中配置:

    <!-- front controller -->      <servlet>          <servlet-name>annomvc</servlet-name>          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>          </servlet>      <servlet-mapping>          <servlet-name>annomvc</servlet-name>          <url-pattern>/</url-pattern>      </servlet-mapping>  


指定Spring来处理请求的Servlet, 默认查找mvc配置文件的地址是:/WEB-INF/${servletName}-servlet.xml, 我们配置的示例中默认查找的mvc配置文件是: /WEB-INF/annomvc-servlet.xml。

B)其他配置文件 spring

这里的其他配置文件,指的是对datasource的配置、persistence层的配置、service层的配置信息等。要加载其他配置文件, 需要在web.xml配置文件中加入一个ContextLoaderListener监听器来配置。ContextLoaderListener只监听初 始化除mvc相关配置之外的bean。代码如下:

    <!-- context load listener -->      <listener>          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>      </listener>  

若没有指定其他参数,默认查找的配置文件位置是:/WEB-INF/applicationContext.xml。

2) 指定配置文件位置

A)修改spring mvc配置文件位置

要修改mvc配置文件的位置,需要在配置DispatcherServlet时指定mvc配置文件的位置。比如想要把annomvc- servlet.xml放到src/config/annomvc-servlet.xml,则需要在配置DispatcherServlet时指 定<init-param>标签。具体代码如下:

</pre></p><p><pre name="code" class="html">    <!-- front controller -->      <servlet>          <servlet-name>annomvc</servlet-name>          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>          <init-param>              <param-name>contextConfigLocation</param-name>              <param-value>classpath:config/annomvc-servlet.xml</param-value>          </init-param>      </servlet>      <servlet-mapping>          <servlet-name>annomvc</servlet-name>          <url-pattern>/</url-pattern>      </servlet-mapping>  


B)修改其他配置文件位置 spring

要修改除mvc配置文件之外的其他bean的配置文件位置,需要在web.xml中加入<context-param>标签,并指定具 体位置。我们有三个配置文件(service-context.xml, persistence-context.xml, datasource-context.xml)他们都位于src/config/文件夹下,那么配置代码如下:

    <!-- context load listener -->      <listener>          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>      </listener>      <context-param>          <param-name>contextConfigLocation</param-name>          <param-value>              classpath:config/service-context.xml              classpath:config/persistence-context.xml              classpath:config/datasource-context.xml              </param-value>      </context-param>


转载位置:http://fyq891014.blog.163.com/blog/static/200740191201233052531278/

0 0
原创粉丝点击