web项目中如何加入spring

      

    在我们使用Spring框架的同时,我们都会在项目中的web.xml中,进行一些Spring的配置,(通过反射完成相应类的调用以及生成)用来在项目使用Spring。下面是几个常用的web.xml中配置spring

1.       org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter

(jpa中的延迟加载过滤器)

属性private String entityManagerFactoryBeanName;用来记录entityManagerFactory的名称值,默认值为entityManagerFactory;

继承OncePerRequestFilter,重写父类的doFilterInternal方法,方法内部主要用来创建一个EntityManagerFactory对象,并调用filterChain.doFilter(request, response);

 

另外,hibernate中的延迟加载过滤器的配置类是

org.springframework.orm.hibernate3.support.OpenSessionInViewFilter()

拥有一个属性private String sessionFactoryBeanName;,默认值是sessionFactory。

实现父类的doFilterInternal方法,主要用来生成sessionFactory对象。

 

2.       org.springframework.web.filter.CharacterEncodingFilter

这是一个过滤器的配置,类中有两个属性,如下:

private String encoding;

private boolean forceEncoding = false;

还有一个重写父类OncePerRequestFilter的doFilterInternal的方法,如下:

@Override

    protected void doFilterInternal(

           HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)

           throws ServletException, IOException {

 

       if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {

           request.setCharacterEncoding(this.encoding);

           if (this.forceEncoding) {

              response.setCharacterEncoding(this.encoding);

           }

       }

       filterChain.doFilter(request, response);

}

此过滤器用来设置request/response的编码(encoding),

1)  当request未设置编码时,或者在web.xml中配置了forceEncoding为true时,并且在web.xml中配置了encoding属性编码的值,这时,会将request中的编码值改为web中配置的编码值。

2)在满足1)的条件下,并且在web中配置的Encoding的编码值为true时,将Response的编码值也设为web中配置的编码值。

3.       org.springframework.web.context.ContextLoaderListener

这个过滤器是当web容器启动时,也启动spring,并通过在web.xml中通过contextConfigLocation的配置,查找对应配置的文件,并建立相应的bean。

  网上关于这方面的内容很多。这里放两个链接。

  spring配置的总体思想

  代码一步步查看理解这个ContextLoad而Listener的实现 (这个源代码的查看,理解,得多练习啊)

4.       org.springframework.web.util.Log4jConfigListener

实现ServletContextListener接口,通过调用类Log4jWebConfigurer的initLogging,和shutdownLogging的两个方法实现接口中的contextInitialized和contextDestroyed方法。

 

 

 

posted @ 2013-01-22 16:29  Thriller1  Views(609)  Comments(0Edit  收藏  举报