springMvc配置文件

来源:互联网 发布:大数据时代 百度云 编辑:程序博客网 时间:2024/05/16 19:43

虽然一直用springMvc,但还是有些基本知识点有误区。
springmvc为什么有多个配置文件,为什么这些配置文件不能写到同一个文件里面,如果你懂了肯定就知道,所有文件写一个一个配置文件里面不好维护,模块化的配置导致不同的配置文件是趋势。

我们来看web.xml 里面
我们都知道listener是spring的入口,
springServlet是用来获取springmvc controller里面的信息 。

<context-param>        <param-name>contextConfigLocation</param-name>        <!-- 本地用的spring配置项 -->        <param-value>classpath:/youdao/spring-context*.xml</param-value></context-param>    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener><servlet>        <servlet-name>springMvc</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <!-- 本地用的spring配置项-->             <param-value>classpath:/youdao/youdaospring-dispatcherservlet.xml</param-value>         </init-param></servlet><servlet-mapping>        <servlet-name>springMvc</servlet-name>        <url-pattern>*.do</url-pattern></servlet-mapping><servlet-mapping>        <servlet-name>springMvc</servlet-name>        <url-pattern>/yd/*</url-pattern></servlet-mapping>

如果在web.xml中不写任何参数配置信息,默认的路径是”/WEB-INF/applicationContext.xml,在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml。如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数:在 里指定相应的xml文件名,如果有多个xml文件,可以写在一起并一“,”号分隔。

如果我们没有在web.xml里面配置springServlet的具体文件地址那么
默认为WEB-INF目录下,名称为[]-servlet.xml,如spring-servlet.xml

我们来看一个完整的

<!-- Spring MVC配置 --><!-- ====================================== --><servlet>    <servlet-name>spring</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml    <init-param>        <param-name>contextConfigLocation</param-name>        <param-value>/WEB-INF/spring-servlet.xml</param-value>&nbsp; 默认    </init-param>    -->    <load-on-startup>1</load-on-startup></servlet><servlet-mapping>    <servlet-name>spring</servlet-name>    <url-pattern>*.do</url-pattern></servlet-mapping><!-- Spring配置 --><!-- ====================================== --><listener>   <listenerclass>     org.springframework.web.context.ContextLoaderListener   </listener-class></listener><!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 --><context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:config/applicationContext.xml</param-value></context-param>

spring.servlet.xml里面主要扫描的是controller的信息,然后回设定一个返回格式、视图文件解析、视图文件解析

<context:component-scan base-package="com.thinkgem.jeesite" use-default-filters="false"><!-- base-package 如果多个,用“,”分隔 -->        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>    </context:component-scan>

而application.xml里面配置有 数据库信息、事务、开启注解啊 等等。加载的这些都是spring上下文用来的信息

所以我们千万不要把application.xml 和spring-servlet.xml里面内容弄混淆 ,也不要把他们加载顺序弄混淆。
application.xml是上下文,配置在listener的参数
spring-servlet.xml 是servlet的参数

最后来个完整的jeesite的配置文件。

spring-context.xml(等于application.xml)

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"      xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"    default-lazy-init="true">    <description>Spring Configuration</description>    <!-- 加载配置属性文件 -->    <context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties" />    <!-- 加载应用属性实例,可通过  @Value("#{APP_PROP['jdbc.driver']}") String jdbcDriver 方式引用 -->    <util:properties id="APP_PROP" location="classpath:jeesite.properties" local-override="true"/>    <!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。  -->    <context:component-scan base-package="com.thinkgem.jeesite"><!-- base-package 如果多个,用“,”分隔 -->        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>    </context:component-scan>    <!-- MyBatis begin -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource" ref="dataSource"/>        <property name="typeAliasesPackage" value="com.thinkgem.jeesite"/>        <property name="typeAliasesSuperType" value="com.thinkgem.jeesite.common.persistence.BaseEntity"/>        <property name="mapperLocations" value="classpath:/mappings/**/*.xml"/>        <property name="configLocation" value="classpath:/mybatis-config.xml"></property>    </bean>    <!-- 扫描basePackage下所有以@MyBatisDao注解的接口 -->    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />        <property name="basePackage" value="com.thinkgem.jeesite"/>       <!--  annotationClass:配置了该注解的dao才会被扫描器扫描,与basePackage是与的作用-->        <property name="annotationClass" value="com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao"/>    </bean>    <!-- 定义事务 -->    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource" />    </bean>    <!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务  -->    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>    <!-- MyBatis end -->    <!-- 配置 JSR303 Bean Validator 定义 -->    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />    <!-- 缓存配置 -->    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">        <property name="configLocation" value="classpath:${ehcache.configFile}" />    </bean>    <!-- 计划任务配置,用 @Service @Lazy(false)标注类,用@Scheduled(cron = "0 0 2 * * ?")标注方法 -->    <task:executor id="executor" pool-size="10"/> <task:scheduler id="scheduler" pool-size="10"/>    <task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true"/>    <!-- 数据源配置, 使用 BoneCP 数据库连接池 -->    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">         <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->        <property name="driverClassName" value="${jdbc.driver}" />        <!-- 基本属性 url、user、password -->        <property name="url" value="${jdbc.url}" />        <property name="username" value="${jdbc.username}" />        <property name="password" value="${jdbc.password}" />        <!-- 配置初始化大小、最小、最大 -->        <property name="initialSize" value="${jdbc.pool.init}" />        <property name="minIdle" value="${jdbc.pool.minIdle}" />         <property name="maxActive" value="${jdbc.pool.maxActive}" />        <!-- 配置获取连接等待超时的时间 -->        <property name="maxWait" value="60000" />        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->        <property name="timeBetweenEvictionRunsMillis" value="60000" />        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->        <property name="minEvictableIdleTimeMillis" value="300000" />        <property name="validationQuery" value="${jdbc.testSql}" />        <property name="testWhileIdle" value="true" />        <property name="testOnBorrow" value="false" />        <property name="testOnReturn" value="false" />        <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)        <property name="poolPreparedStatements" value="true" />        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->        <!-- 配置监控统计拦截的filters -->        <property name="filters" value="stat" />     </bean>    <!-- 数据源配置, 使用应用服务器的数据库连接池     <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/jeesite" />-->    <!-- 数据源配置, 不使用连接池     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="driverClassName" value="${jdbc.driver}" />        <property name="url" value="${jdbc.url}" />        <property name="username" value="${jdbc.username}"/>        <property name="password" value="${jdbc.password}"/>    </bean>-->    <!--  -->    <bean id="clear" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >         <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->        <property name="driverClassName" value="${jdbc2.driver}" />        <!-- 基本属性 url、user、password -->        <property name="url" value="${jdbc2.url}" />        <property name="username" value="${jdbc2.username}" />        <property name="password" value="${jdbc2.password}" />    </bean></beans>

springmvc.xml(等于spring-servlet.xml)

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">    <description>Spring MVC Configuration</description>    <!-- 加载配置属性文件 -->    <context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties" />    <!-- 使用Annotation自动注册Bean,只扫描@Controller -->    <context:component-scan base-package="com.thinkgem.jeesite" use-default-filters="false"><!-- base-package 如果多个,用“,”分隔 -->        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>    </context:component-scan>    <!-- 默认的注解映射的支持,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping -->    <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">        <mvc:message-converters register-defaults="true">            <!-- 将StringHttpMessageConverter的默认编码设为UTF-8 -->            <bean class="org.springframework.http.converter.StringHttpMessageConverter">                <constructor-arg value="UTF-8" />            </bean>            <!-- 将Jackson2HttpMessageConverter的默认格式化输出为false -->            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">                <property name="supportedMediaTypes">                    <list><value>application/json;charset=UTF-8</value></list>                </property>                <property name="prettyPrint" value="false"/>                <property name="objectMapper">                      <bean class="com.thinkgem.jeesite.common.mapper.JsonMapper"></bean>                  </property>             </bean>            <!-- 使用XML格式输出数据 -->            <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">                <constructor-arg>                    <bean class="org.springframework.oxm.xstream.XStreamMarshaller">                        <property name="streamDriver">                            <bean class="com.thoughtworks.xstream.io.xml.StaxDriver"/>                        </property>                        <property name="annotatedClasses">                            <list>                                <value>com.thinkgem.jeesite.common.persistence.BaseEntity</value>                                <value>com.thinkgem.jeesite.common.supcan.treelist.TreeList</value>                                <value>com.thinkgem.jeesite.common.supcan.treelist.cols.Col</value>                                <value>com.thinkgem.jeesite.common.supcan.treelist.cols.Group</value>                            </list>                        </property>                    </bean>                </constructor-arg>                <property name="supportedMediaTypes" value="application/xml"></property>            </bean>        </mvc:message-converters>    </mvc:annotation-driven>    <!-- REST中根据URL后缀自动判定Content-Type及相应的View -->    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">        <property name="mediaTypes" >            <map>                 <entry key="xml" value="application/xml"/>                 <entry key="json" value="application/json"/>             </map>        </property>        <property name="ignoreAcceptHeader" value="true"/>        <property name="favorPathExtension" value="true"/>    </bean>    <!-- 定义视图文件解析 -->    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="${web.view.prefix}"/>        <property name="suffix" value="${web.view.suffix}"/>    </bean>    <!-- 对静态资源文件的访问, 将无法mapping到Controller的path交给default servlet handler处理 -->    <mvc:default-servlet-handler />    <!-- 静态资源映射 -->    <mvc:resources mapping="/static/**" location="/static/" cache-period="31536000"/>    <!-- 定义无Controller的path<->view直接映射 -->    <mvc:view-controller path="/" view-name="redirect:${web.view.index}"/>    <!-- 拦截器配置,拦截顺序:先执行后定义的,排在第一位的最后执行。-->    <mvc:interceptors>        <mvc:interceptor>            <mvc:mapping path="${adminPath}/**" />            <mvc:exclude-mapping path="${adminPath}/"/>            <mvc:exclude-mapping path="${adminPath}/login"/>            <mvc:exclude-mapping path="${adminPath}/sys/menu/tree"/>            <mvc:exclude-mapping path="${adminPath}/sys/menu/treeData"/>            <mvc:exclude-mapping path="${adminPath}/oa/oaNotify/self/count"/>            <bean class="com.thinkgem.jeesite.modules.sys.interceptor.LogInterceptor" />        </mvc:interceptor>        <!-- 手机视图拦截器 -->        <mvc:interceptor>            <mvc:mapping path="/**" />            <bean class="com.thinkgem.jeesite.modules.sys.interceptor.MobileInterceptor" />        </mvc:interceptor>    </mvc:interceptors>    <!-- 支持Shiro对Controller的方法级AOP安全控制 begin-->    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">        <property name="proxyTargetClass" value="true" />    </bean>    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">        <property name="exceptionMappings">            <props>                <prop key="org.apache.shiro.authz.UnauthorizedException">error/403</prop>                <prop key="java.lang.Throwable">error/500</prop>            </props>            </property>    </bean>    <!-- 支持Shiro对Controller的方法级AOP安全控制 end -->    <!-- 上传文件拦截,设置最大上传文件大小   10M=10*1024*1024(B)=10485760 bytes -->      <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">          <property name="maxUploadSize" value="${web.maxUploadSize}" />      </bean></beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"    version="2.5">    <display-name>JeeSite</display-name>    <!-- Context ConfigLocation -->    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath*:/spring-context*.xml</param-value>    </context-param>    <listener>        <listener-class>com.thinkgem.jeesite.modules.sys.listener.WebContextListener</listener-class>    </listener>    <listener>        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>      </listener>    <filter>        <filter-name>encodingFilter</filter-name>        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>        <init-param>            <param-name>encoding</param-name>            <param-value>UTF-8</param-value>        </init-param>        <init-param>            <param-name>forceEncoding</param-name>            <param-value>true</param-value>        </init-param>    </filter>    <filter-mapping>        <filter-name>encodingFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    <!-- Apache Shiro -->    <filter>        <filter-name>shiroFilter</filter-name>        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>        <init-param>            <param-name>targetFilterLifecycle</param-name>            <param-value>true</param-value>        </init-param>    </filter>    <filter-mapping>        <filter-name>shiroFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    <!-- PageCache, cache .html suffix.    <filter>        <filter-name>PageCacheFilter</filter-name>        <filter-class>com.thinkgem.jeesite.common.filter.PageCachingFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>PageCacheFilter</filter-name>        <url-pattern>/</url-pattern>    </filter-mapping>    <filter-mapping>        <filter-name>PageCacheFilter</filter-name>        <url-pattern>*.html</url-pattern>    </filter-mapping>-->    <!-- SiteMesh -->    <filter>        <filter-name>sitemeshFilter</filter-name>        <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>sitemeshFilter</filter-name>        <url-pattern>/a/*</url-pattern>    </filter-mapping>    <filter-mapping>        <filter-name>sitemeshFilter</filter-name>        <url-pattern>/f/*</url-pattern>    </filter-mapping>    <!-- MVC Servlet -->    <servlet>        <servlet-name>springServlet</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath*:/spring-mvc*.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>springServlet</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping>    <!-- Activiti -->    <servlet>        <servlet-name>RestletServlet</servlet-name>        <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>        <init-param>            <param-name>org.restlet.application</param-name>            <param-value>com.thinkgem.jeesite.modules.act.rest.ActRestApplication</param-value>        </init-param>    </servlet>    <servlet-mapping>        <servlet-name>RestletServlet</servlet-name>        <url-pattern>/act/rest/service/*</url-pattern>    </servlet-mapping>    <!-- DruidStatView -->    <servlet>        <servlet-name>DruidStatView</servlet-name>        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>        <init-param>            <param-name>allow</param-name>            <param-value>127.0.0.1</param-value>        </init-param>    </servlet>    <servlet-mapping>        <servlet-name>DruidStatView</servlet-name>        <url-pattern>/druid/*</url-pattern>    </servlet-mapping>    <!-- CKFinder -->    <servlet>        <servlet-name>CKFinderConnectorServlet</servlet-name>        <servlet-class>com.thinkgem.jeesite.common.web.CKFinderConnectorServlet</servlet-class>        <init-param>            <param-name>XMLConfig</param-name>            <param-value>/WEB-INF/ckfinder.xml</param-value>        </init-param>        <init-param>            <param-name>debug</param-name>            <param-value>false</param-value>        </init-param>        <init-param>            <param-name>configuration</param-name>            <param-value>com.thinkgem.jeesite.common.web.CKFinderConfig</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>CKFinderConnectorServlet</servlet-name>        <url-pattern>/static/ckfinder/core/connector/java/connector.java</url-pattern>    </servlet-mapping>    <filter>        <filter-name>FileUploadFilter</filter-name>        <filter-class>com.ckfinder.connector.FileUploadFilter</filter-class>        <init-param>            <param-name>sessionCookieName</param-name>            <param-value>JSESSIONID</param-value>        </init-param>        <init-param>            <param-name>sessionParameterName</param-name>            <param-value>jsessionid</param-value>        </init-param>    </filter>    <filter-mapping>        <filter-name>FileUploadFilter</filter-name>        <url-pattern>/static/ckfinder/core/connector/java/connector.java</url-pattern>    </filter-mapping>    <!-- Userfiles download -->    <servlet>        <servlet-name>UserfilesDownloadServlet</servlet-name>        <servlet-class>com.thinkgem.jeesite.common.servlet.UserfilesDownloadServlet</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>UserfilesDownloadServlet</servlet-name>        <url-pattern>/userfiles/*</url-pattern>    </servlet-mapping>    <!-- Validate code -->    <servlet>        <servlet-name>ValidateCodeServlet</servlet-name>        <servlet-class>com.thinkgem.jeesite.common.servlet.ValidateCodeServlet</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>ValidateCodeServlet</servlet-name>        <url-pattern>/servlet/validateCodeServlet</url-pattern>    </servlet-mapping>    <!-- FineReport -->    <servlet>        <servlet-name>ReportServer</servlet-name>        <servlet-class>com.fr.web.ReportServlet</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>ReportServer</servlet-name>        <url-pattern>/ReportServer</url-pattern>    </servlet-mapping>    <!-- [INSERT FRAGMENT HERE] -->    <!-- Session configure, to "jeesite.properties" file "session.sessionTimeout" parameter.    <session-config>        <session-timeout>30</session-timeout>    </session-config>-->    <!-- Error page -->    <!-- <error-page>        <exception-type>java.lang.Throwable</exception-type>        <location>/WEB-INF/views/error/500.jsp</location>    </error-page> -->    <!--500系列错误代码是对方网站服务器问题  -->    <error-page>        <error-code>500</error-code>        <location>/WEB-INF/views/error/500.jsp</location>    </error-page>    <error-page>        <error-code>404</error-code>        <location>/WEB-INF/views/error/404.jsp</location>    </error-page></web-app>
0 0
原创粉丝点击