1.ContextLoaderListener

对于使用Spring的Web应用,无需手动创建Spring容器,而是通过配置文件声明式地创建Spring容器。可以直接在web.xml文件中配置创建Spring容器。

Spring提供了一个ContextLoaderListener,该监听器类实现了ServletContextListener接口,它会在创建时自动查找WEB-INF/下的applicationContext.xml文件。因此,如果只有一个配置文件,且文件名为applicationContext.xml,则只需在web.xml文件中增加如下配置片段即可。

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

如果有多个配置文件需要载入,则考虑使用<context-param…/>元素来确定配置文件的文件名。

ContextLoaderListener加载时会查找名为contextConfigLocation的初始化参数,如下:

<!--指定多个配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-context.xml,
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<!--使用ContextLoaderListener初始化Spring容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

如果没有使用contextConfigLocation指定配置文件,则Spring会自动查找WEB-INF/下的applicationContext.xml文件。

如果有contextConfigLocation,则使用该参数确定的配置文件。

如果无法找到合适的配置文件,Spring将无法正常初始化。

2.可能遇到的异常

在配置Spring MVC时,可能会遇到这样的错误:

org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessioorg.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current threadnContext.java:134)

那么在web.xml文件中添加如下配置即可:

<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

OpenSessionInViewFilter的主要功能是用来把一个Hibernate Session和一次完整的请求过程对应的线程相绑定。

Open Session In View在request把session绑定到当前thread期间一直保持hibernate session在open状态,使session在request的整个期间都可以使用。当View 层逻辑完成后,才会通过Filter的doFilter方法或Interceptor的postHandle方法自动关闭session。

最新文章

  1. MySQL存储引擎--MyISAM与InnoDB区别
  2. ArcGIS 使用点滴记录
  3. solr使用
  4. backgroundworker的应用
  5. 【LeetCode】Best Time to Buy and Sell Stock IV
  6. vsftp.conf
  7. hdu 1853 Cyclic Tour 最小费用最大流
  8. 读Qt Demo&mdash;&mdash;Basic Layouts Example
  9. C++多态性与C#的比较
  10. WPF——控件之间的绑定
  11. javascript中的function对象
  12. HDU 4612 (13年多校第二场1002)无向图缩点,有重边
  13. EF操作sqlite数据库时的项目兼容性问题
  14. Cesium原理篇:3D Tiles(3)个人总结
  15. 201521123026 《Java程序设计》第5周学习总结
  16. Java开发速度神器Lombok,Eclipse端安装使用教程
  17. 小步快跑的公司可以最简化操作直接通过log4net将日志写入ElasticSearch
  18. C# 乐观锁、悲观锁、共享锁、排它锁、互斥锁
  19. (转载)基于Unity~UGUI的简单UI框架(附UIFramework源码)
  20. linux系统,服务器与服务器拷贝文件

热门文章

  1. List、Map、Set三个接口存储元素时各有什么特点?
  2. markDownPad Key
  3. 【Python】IDLE清屏
  4. Python+selenium之读取配置文件内容
  5. C/C++程序内存分配详解
  6. [Navicat] 常用快捷键及注意事项
  7. Thrift初试
  8. MySQL 索引性能分析概要
  9. pro_select_roleinfo_p3
  10. 面试常见的selenium问题