spring应用中web.xml的设置

来源:互联网 发布:北京碧水源 知乎 编辑:程序博客网 时间:2024/05/17 22:39

加载spring的配置文件

<context-param>

   <param-name>contextConfigLocation</param-name>

   <param-value>classpath*:spring/*.xml</param-value>

 </context-param>

Spring常用的两个监听器:

<!-- 在自己所定义的Servlet类别中使用Spring的容器功能, ContextLoaderListener预设会读取context-param中指定的配置文件à

<listener>

   <listener-class>

                            org.springframework.web.context.ContextLoaderListener

                   </listener-class>

 </listener>

<!--Introspector 缓存清除监听器-->

Spring 还提供了一个名为 org.springframework.web.util.IntrospectorCleanupListener 的监听器。它主要负责处理由 JavaBean Introspector 功能而引起的缓存泄露。IntrospectorCleanupListener 监听器在 Web 应用关闭的时会负责清除 JavaBean Introspector 的缓存,在 web.xml 中注册这个监听器可以保证在 Web 应用关闭的时候释放与其相关的 ClassLoader 的缓存和类引用。如果您使用了 JavaBean Introspector 分析应用中的类,Introspector 缓存会保留这些类的引用,结果在应用关闭的时候,这些类以及 Web 应用相关的 ClassLoader 不能被垃圾回收。不幸的是,清除 Introspector 的唯一方式是刷新整个缓存,这是因为没法准确判断哪些是属于本 Web 应用的引用对象,哪些是属于其它 Web 应用的引用对象。所以删除被缓存的 Introspection 会导致将整个 JVM 所有应用的 Introspection 都删掉。需要注意的是,Spring 托管的 Bean 不需要使用这个监听器,因为 Spring 的 Introspection 所使用的缓存在分析完一个类之后会马上从 javaBean Introspector 缓存中清除掉,并将缓存保存在应用程序特定的 ClassLoader 中,所以它们一般不会导致内存资源泄露。但是一些类库和框架往往会产生这个问题。例如 Struts 和 Quartz 的 Introspector 的内存泄漏会导致整个的 Web 应用的 ClassLoader 不能进行垃圾回收。在 Web 应用关闭之后,您还会看到此应用的所有静态类引用,这个错误当然不是由这个类自身引起的。解决这个问题的方法很简单,您仅需在 web.xml 中配置 IntrospectorCleanupListener 监听器就可以了

 <listener>

   <listener-class>

                            org.springframework.web.util.IntrospectorCleanupListener

                   </listener-class>

 </listener>

WebAppRootListener 监听器配置

 <context-param> 

     <param-name>webAppRootKey</param-name> 

     <param-value>web.root</param-value> ① Web 应用根目录以该属性名添加到系统参数中

 </context-param> 

② 负责将 Web 应用根目录以 webAppRootKey 上下文参数指定的属性名添加到系统参数中

 <listener>  

     <listener-class> 

    org.springframework.web.util.WebAppRootListener  

     </listener-class> 

 </listener> 

 

设置日志的跟踪:

① 指定 Log4J 配置文件的地址

<context-param>    

 <param-name>log4jConfigLocation</param-name> 

 <param-value>/WEB-INF/log4j.properties</param-value>  

</context-param> 

② 使用该监听器初始化 Log4J 日志引擎 

<listener> 

    <listener-class>     org.springframework.web.util.Log4jConfigListener     </listener-class>  

</listener> 

  通过${web.root}可以获取到系统的跟路径


 <!--常用的过滤器, 中文乱码过滤器-->

 <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>   过滤器的匹配 URL

   <filter-name>encodingFilter</filter-name>

   <url-pattern>/*</url-pattern>

 </filter-mapping>