将全部对象的建立与管理任务交给Spring容器,下降程序的耦合度。web
将Spring容器注入到Web容器中。spring
使用ServletContextListener监听ServletContext,当ServletContexxt建立时同时建立Spring容器,并将建立完成的容器放到ServletContext即application中,在Web中获取Spring容器,就能够访问对象了。ContextLoadListener是ServletContextListener的一个实现类,配置:数据库
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
默认状况下,Spring的配置文件只能放在WEB-INF目录下,名称为applicationContext.xml,能够在web.xml文件中修改,将配置文件放在src目录下:app
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:xxxx.xml</param-value> </context>
WebApplicationContext context=WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
表示层调用Service层方法从数据库中加载对象,若是Dao层采用了延时加载,返回一个包含null对象的代理,在视图层访问对象的详情时,Service层已经执行完毕,事务已关闭,对象为空,就没法获取对象的详情。ui
将Session与请求线程绑定,容许在事务关闭之后完成延时加载任务。url
在web.xml中配置:spa
<filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>opernSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>