Spring与Web整合 Spring与Web整合实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring与Web整合 Spring与Web整合实例

  2021-03-24 我要评论
想了解Spring与Web整合实例的相关内容吗,在本文为您仔细讲解Spring与Web整合的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Spring与Web整合,下面大家一起来学习吧。

一 概述

1.整合目的

将所有对象的创建与管理任务交给Spring容器,降低程序的耦合度。

2.整合途径

将Spring容器注入到Web容器中。

3.具体实现

使用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目录下:

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:xxxx.xml</param-value>
</context>

4.获取Spring容器

WebApplicationContext context=WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

二 延时加载问题

1.原因

视图层调用Service的方法从数据库中加载对象,如果Dao实现层采用了延时加载,返回一个包含null对象的代理,在视图层访问对象的详情时,Service层已经执行完毕,事务已关闭,对象为空,就无法获取对象的详情。

2.解决方法

将Session与请求线程绑定,允许在事务关闭以后完成延时加载任务。

3.具体实现

在web.xml中配置:

<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>

以上这篇Spring与Web整合实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们