ssh2集成
先创建一个ssh2的项目
pom
1.1 hibernate相关(5.2.12.Final)
hibernate-core
hibernate-c3p0(数据库连接池)
hibernate-ehcache
mysql-connector-java(5.1.44)
1.2 spring相关(5.0.1.RELEASE)
spring-context
spring-orm
spring-web
spring-aspects
注:创建spring的XML文件时,需要添加beans/aop/tx/context标签支持
各依赖说明:
spring-context
创建spring上下文
spring-orm
org.springframework.orm.hibernate5.LocalSessionFactoryBean
dataSource:指定数据源
hibernateProperties:指定hibernate相关属性,如:dialect/show_sql/format_sql
mappingResources:指定实体映射文件
注1:本章采用将hibernate配置全部交给spring管理,因此项目中不再有hibernate.cfg.xml文件
org.springframework.orm.hibernate5.HibernateTemplate
org.springframework.orm.hibernate5.support.HibernateDaoSupport
测试一:运行测试类Test1,测试hibernate与spring的集成
spring-web
org.springframework.web.context.ContextLoaderListener
contextConfigLocation:classpath:applicationContext-*.xml
org.springframework.web.context.support.WebApplicationContextUtils
测试二:访问test2.jsp,测试spring与WEB项目的集成
spring-aspects
spring的AspectJ依赖,解析事务切点
1.3 struts2相关(2.5.13)
struts2-core
struts2-spring-plugin
struts2与spring集成的插件
将action配置到spring中,struts的action标签的class属性填写spring中bean的名字或id
1.4 log配置
1.4.1 log4j(1.X版)
不建议使用
1.4.2 log4j2(2.9.1)
log4j-core
log4j-api
log4j-web
不建议使用
1.4.3 log4j2 + slf4j(使用ehcache开启hibernate二级缓存必须使用第二种方式配置日志)
注1:本章使用第三种方式配置日志,即log4j2 + slf4j
1.5 other
junit(4.12)
javax.servlet-api(4.0.0)
1.6 jstl
jstl(1.2)
standard(1.1.2)
1.7 jsp自定义标签依赖(必须与tomcat的版本一致)
tomcat-jsp-api
注1:如何解决项目中不支持EL表达式的问题?将web.xml的DTD的版本由2.3升级到3.0即可。因为web2.3是不支持EL表达式的
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zking</groupId>
<artifactId>ssh2</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>ssh2 Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<!-- 1.hibernate -->
<hibernate.version>5.2.12.Final</hibernate.version>
<!-- MySQL -->
<MySQL.version>5.1.44</MySQL.version>
<!-- ehcache -->
<ehcache.version>2.10.0</ehcache.version>
<!-- 2.spring -->
<spring.version>5.0.1.RELEASE</spring.version>
<!-- 3.struts2 -->
<struts2.version>2.5.13</struts2.version>
<!-- 4.log日志(log4j2+lsf4j) -->
<slf4j.version>1.7.7</slf4j.version>
<log4j2.version>2.9.1</log4j2.version>
<log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
<!-- 5.junit+servlet -->
<junit.version>4.12</junit.version>
<servlet.version>4.0.1</servlet.version>
<!-- 6.jstl+standard -->
<jstl.version>1.2</jstl.version>
<standard.version>1.1.2</standard.version>
<!-- 7.tomcat-jsp -->
<tomcat.jsp.version>8.0.46</tomcat.jsp.version>
<!-- 8.jackson -->
<jackson.version>2.10.0</jackson.version>
</properties>
<dependencies>
<!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- hibernate-c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- hibernate-ehcache -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${MySQL.version}</version>
</dependency>
<!-- ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
</dependency>
<!-- spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- struts2-core -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts2.version}</version>
</dependency>
<!-- struts2-spring-plugin -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>${struts2.version}</version>
</dependency>
<!-- log配置:Log4j2 + Slf4j -->
<!-- slf4j核心包 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<!--用于与slf4j保持桥接 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!--核心log4j2jar包 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!--web工程需要包含log4j-web,非web工程不需要 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>${log4j2.version}</version>
<scope>runtime</scope>
</dependency>
<!--需要使用log4j2的AsyncLogger需要包含disruptor -->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>${log4j2.disruptor.version}</version>
</dependency>
<!-- 5.junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- 5.servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!-- 6.jstl+standard -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${standard.version}</version>
</dependency>
<!-- 7.tomcat-jsp-api -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>8.5.56</version>
</dependency>
<!-- 8.jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>
<finalName>ssh2</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
SSH2集成
1 导入ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存-->
<!--path:指定在硬盘上存储对象的路径-->
<!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));-->
<diskStore path="java.io.tmpdir"/>
<!--defaultCache:默认的管理策略-->
<!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断-->
<!--maxElementsInMemory:在内存中缓存的element的最大数目-->
<!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上-->
<!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false-->
<!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问-->
<!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问-->
<!--memoryStoreEvictionPolicy:缓存的3 种清空策略-->
<!--FIFO:first in first out (先进先出)-->
<!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存-->
<!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存-->
<defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
<!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)-->
<!-- <cache name="stuCache" eternal="false" maxElementsInMemory="100"
overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/> -->
</ehcache>
2 导入log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- status : 指定log4j本身的打印日志的级别.ALL< Trace < DEBUG < INFO < WARN < ERROR
< FATAL < OFF。 monitorInterval : 用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s. -->
<Configuration status="WARN" monitorInterval="30">
<Properties>
<!-- 配置日志文件输出目录 ${sys:user.home} -->
<Property name="LOG_HOME">/root/workspace/lucenedemo/logs</Property>
<property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/error</property>
<property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warn</property>
<property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n</property>
</Properties>
<Appenders>
<!--这个输出控制台的配置 -->
<Console name="Console" target="SYSTEM_OUT">
<!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
<ThresholdFilter level="trace" onMatch="ACCEPT"
onMismatch="DENY" />
<!-- 输出日志的格式 -->
<!-- %d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间 %p : 日志输出格式 %c : logger的名称
%m : 日志内容,即 logger.info("message") %n : 换行符 %C : Java类名 %L : 日志输出所在行数 %M
: 日志输出所在方法名 hostName : 本地机器名 hostAddress : 本地ip地址 -->
<PatternLayout pattern="${PATTERN}" />
</Console>
<!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
<!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true -->
<File name="log" fileName="logs/test.log" append="false">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</File>
<!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size, 则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
<RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
<ThresholdFilter level="info" onMatch="ACCEPT"
onMismatch="DENY" />
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
<Policies>
<!-- 基于时间的滚动策略,interval属性用来指定多久滚动一次,默认是1 hour。 modulate=true用来调整时间:比如现在是早上3am,interval是4,那么第一次滚动是在4am,接着是8am,12am...而不是7am. -->
<!-- 关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval, 日期格式精确到哪一位,interval也精确到哪一个单位 -->
<!-- log4j2的按天分日志文件 : info-%d{yyyy-MM-dd}-%i.log -->
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
<!-- SizeBasedTriggeringPolicy:Policies子节点, 基于指定文件大小的滚动策略,size属性用来定义每个日志文件的大小. -->
<!-- <SizeBasedTriggeringPolicy size="2 kB" /> -->
</Policies>
</RollingFile>
<RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
<ThresholdFilter level="warn" onMatch="ACCEPT"
onMismatch="DENY" />
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="2 kB" />
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
<DefaultRolloverStrategy max="20" />
</RollingFile>
<RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
<ThresholdFilter level="error" onMatch="ACCEPT"
onMismatch="DENY" />
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
<Policies>
<!-- log4j2的按分钟 分日志文件 : warn-%d{yyyy-MM-dd-HH-mm}-%i.log -->
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
<!-- <SizeBasedTriggeringPolicy size="10 MB" /> -->
</Policies>
</RollingFile>
</Appenders>
<!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
<Loggers>
<!--过滤掉spring和mybatis的一些无用的DEBUG信息 -->
<logger name="org.springframework" level="INFO"></logger>
<logger name="org.mybatis" level="INFO"></logger>
<!-- 第三方日志系统 -->
<logger name="org.springframework" level="ERROR" />
<logger name="org.hibernate" level="ERROR" />
<logger name="org.apache.struts2" level="ERROR" />
<logger name="com.opensymphony.xwork2" level="ERROR" />
<logger name="org.jboss" level="ERROR" />
<!-- 配置日志的根节点 -->
<root level="all">
<appender-ref ref="Console" />
<appender-ref ref="RollingFileInfo" />
<appender-ref ref="RollingFileWarn" />
<appender-ref ref="RollingFileError" />
</root>
</Loggers>
</Configuration>
3 集成hibernate
1.1 注入数据库配置文件
db.properties
db.username=root
db.password=
db.driverClass=com.mysql.jdbc.Driver
db.jdbcUrl=jdbc:mysql://localhost:3306/t243
db.initialPoolSize=10
db.maxPoolSize=20
db.minPoolSize=5
db.maxIdleTime=60
db.acquireIncrement=5
db.maxStatements=0
db.idleConnectionTestPeriod=60
db.acquireRetryAttempts=30
db.breakAfterAcquireFailure=true
db.testConnectionOnCheckout=false
1.2 配置c3p0连接池
1.3 注册LocalSessionFactoryBean
1.4 spring声明式事物
声明式事务配置
1) 必须先修改spring配置文件的声明部分,添加对aop标签和tx标签的支持
-
配置SessionFactory(spring和hibernate集成时已完成)
-
配置事务管理器
HibernateTransactionManager -
配置事务的传播特性(tx)
add
edit
del
load|list
事务传播特性(PROPAGATION_REQUIRED|readOnly) -
配置自动代理
a) 引用环绕通知txAdvice
b) 定义一个切入点
execution(* *…Biz.(…))
a:返回值不限 b:包名不限 c:接口名以Biz结尾 d:方法名及参数不限
c) 自动代理的原理
在spring上下文初始化完成以后,自动代理会逐个检查spring上下文中JavaBean实现的接口是否满足自动代理的条件,如果满足条件,则将此bean和通知结合生成一个代理对象,并以此代理对象替换spring上下文中的bean,之后你访问的就是代理对象了
applicationContext-hibernate.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 集成:
1 注入数据库配置文件
2 配置c3p0连接池
3 注册LocalSessionFactoryBean
4 spring声明式事物
5 开启动态代理
6 注册HibernateTemplate
7 注册Base模块(分包分模块开发)
-->
<!-- 1 注入数据库配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 2 配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
<property name="driverClass" value="${db.driverClass}"></property>
<property name="jdbcUrl" value="${db.jdbcUrl}"></property>
<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="${db.initialPoolSize}"></property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="${db.maxPoolSize}"></property>
<!--连接池中保留的最小连接数。 -->
<property name="minPoolSize" value="${db.minPoolSize}" />
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="${db.maxIdleTime}" />
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="${db.acquireIncrement}" />
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。
所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default:
0 -->
<property name="maxStatements" value="${db.maxStatements}" />
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="${db.idleConnectionTestPeriod}" />
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts" value="${db.acquireRetryAttempts}" />
<!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。
如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->
<property name="breakAfterAcquireFailure" value="${db.breakAfterAcquireFailure}" />
<!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod
或automaticTestTable 等方法来提升连接测试的性能。Default: false -->
<property name="testConnectionOnCheckout" value="${db.breakAfterAcquireFailure}" />
</bean>
<!-- 3 注册LocalSessionFactoryBean,Spring与hibernate集成配置用于替换hibernate.cfg.xml-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource">
<ref bean="dataSource" />
</property>
<!-- hibernate相关属性 -->
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
<!--spring与Hibernate集成无法显示sql语句问题,请见集成后hibernate无法显示sql语句.txt-->
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.connection.autocommit">false</prop>
<!-- 开启二级缓存 -->
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<!-- 开启查询缓存 -->
<prop key="hibernate.cache.use_query_cache">true</prop>
<!-- EhCache驱动 -->
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
</props>
</property>
<!-- 实体映射文件 -->
<property name="mappingResources">
<list>
<value>com/tang/book/entity/Book.hbm.xml</value>
</list>
</property>
</bean>
<!-- 4 spring声明式事物 -->
<!--声明式事务配置开始 -->
<!--1) 开启自动代理 -->
<!-- 代理对象=目标+通知 -->
<aop:aspectj-autoproxy />
<!--2) 事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!--3) 定义事务特性 -->
<tx:advice id="txAdvice"
transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="load*" propagation="REQUIRED" read-only="true" />
<tx:method name="list*" propagation="REQUIRED" read-only="true" />
<tx:method name="select*" propagation="REQUIRED" read-only="true" />
<tx:method name="query*" propagation="REQUIRED" read-only="true" />
<tx:method name="do*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!--4) 定义切入点 -->
<!-- 适配器=通知+切入点 -->
<aop:config>
<!-- pointcut属性用来定义一个切入点,分成四个部分理解 [* ][*..][*Biz][.*(..)] -->
<!-- A: 返回类型,*表示返回类型不限 -->
<!-- B: 包名,*..表示包名不限 -->
<!-- C: 类或接口名,*Biz表示类或接口必须以Biz结尾 -->
<!-- D: 方法名和参数,*(..)表示方法名不限,参数类型和个数不限 -->
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* *..*Biz.*(..))" />
</aop:config>
<!-- 声明式事务配置结束 -->
<!-- 5.注册hibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 分包分模块 -->
<bean id="baseDao"
class="com.tang.base.dao.BaseDao"
abstract="true">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
<bean id="baseBiz"
class="com.tang.base.biz.BaseBiz"
abstract="true">
</bean>
<bean id="baseAction"
class="com.tang.base.action.BaseAction"
abstract="true">
</bean>
</beans>
注1:狸猫换太子
1.5 注册HibernateTemplate
1.6 注册Base模块
代码
程序代码的分层
base
1.action
BaseAction
package com.tang.base.action;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class BaseAction implements ServletRequestAware,ServletResponseAware {
//Action中方法返回值定义
public static final String SUCCESS="success";
public static final String FAILED="failed";
public static final String ADD="add";
public static final String EDIT="edit";
public static final String DETAIL="detail";
public static final String LIST="list";
protected HttpServletRequest request;
protected HttpServletResponse response;
protected HttpSession session;
protected ServletContext applicaiton;
//返回结果
public Object result;
//返回消息
public String message;
//结果码 0成功 非0失败
public int code=0;
public String forward;
public String getForward(String defaultForward) {
if(null==forward||"".equals(forward.trim()))
return defaultForward;
return forward;
}
public void setForward(String forward) {
this.forward = forward;
}
public Object getResult() {
return result;
}
public String getMessage() {
return message;
}
public int getCode() {
return code;
}
public BaseAction() {
super();
}
@Override
public void setServletRequest(HttpServletRequest req) {
this.request=req;
this.session=req.getSession();
this.applicaiton=req.getServletContext();
}
@Override
public void setServletResponse(HttpServletResponse resp) {
this.response=resp;
}
public void toJsonMessager(String msg,Boolean flag) {
try {
ObjectMapper mapper=new ObjectMapper();
Map<String, Object> json=new HashMap<String,Object>();
json.put("success", flag);
json.put("msg", msg);
mapper.writeValue(response.getOutputStream(), json);
} catch (Exception e) {
e.printStackTrace();
}
}
public void toJsonData(Object obj,Boolean flag) {
try {
ObjectMapper mapper=new ObjectMapper();
Map<String, Object> json=new HashMap<String,Object>();
json.put("data", obj);
json.put("success", flag);
mapper.writeValue(response.getOutputStream(),json);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.biz
BaseBiz
package com.tang.base.biz;
public abstract class BaseBiz {
}
3.dao
BaseDao
package com.tang.base.dao;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
public abstract class BaseDao extends HibernateDaoSupport {
}
4.entity
5.util
StringUtils
package com.tang.base.util;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(Object s) {
boolean b = false;
if (null == s || s.toString().trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(Object s) {
return !isBlank(s);
}
}
PageBean
package com.tang.base.util;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
public class PageBean {
//页码
private int page=1;
//每页显示多少条记录
private int rows=10;
//总记录数
private int total=0;
//是否分页,分页标记,默认分页
private boolean pagintaion=true;
//上一次的请求路径
private String url;
//上一次的请求参数
private Map<String,String[]> map;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getMap() {
return map;
}
public void setMap(Map<String, String[]> map) {
this.map = map;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public boolean isPagintaion() {
return pagintaion;
}
public void setPagintaion(boolean pagintaion) {
this.pagintaion = pagintaion;
}
public PageBean() {
super();
}
public void setPage(String page) {
if(null!=page&&!"".equals(page))
this.page=Integer.parseInt(page);
}
public void setRows(String rows) {
if(null!=rows&&!"".equals(rows))
this.rows=Integer.parseInt(rows);
}
public void setPagintaion(String pagination) {
if(null!=pagination&&!"".equals(pagination))
this.pagintaion=Boolean.parseBoolean(pagination);
}
/**
* 获取sql语句的开始查询位置
* @return
*/
public int getStartIndex() {
//(1-1)*10=0 limit 0,10
//(2-1)*10=10 limit 10,10
return (this.page-1)*this.rows;
}
/**
* 获取最大页码
* @return
*/
public int getMaxPager() {
int maxPager=this.total/this.rows;
if(this.total%this.rows!=0)
maxPager++;
return maxPager;
}
/**
* 上一页
* @return
*/
public int getProviousPager() {
int provPager=this.page-1;
if(provPager<=1)
provPager=1;
return provPager;
}
/**
* 下一页
* @return
*/
public int getNextPager() {
int nextPager=this.page+1;
if(nextPager>=getMaxPager())
nextPager=getMaxPager();
return nextPager;
}
public void setRequest(HttpServletRequest req) {
String page=req.getParameter("page");
String rows=req.getParameter("rows");
String pagination=req.getParameter("pagintaion");
//设置参数
this.setPage(page);
this.setRows(rows);
this.setPagintaion(pagination);
//设置url请求路径
this.url=req.getRequestURI();
//设置请求参数
this.map=req.getParameterMap();
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagintaion=" + pagintaion
+ ", url=" + url + ", map=" + map + "]";
}
}
book
1.action
BookAction
package com.tang.book.action;
import java.util.List;
import com.opensymphony.xwork2.ModelDriven;
import com.tang.base.action.BaseAction;
import com.tang.base.util.PageBean;
import com.tang.book.biz.IBookBiz;
import com.tang.book.entity.Book;
public class BookAction extends BaseAction implements ModelDriven<Book> {
Book book=new Book();
private IBookBiz bookBiz;
public IBookBiz getBookBiz() {
return bookBiz;
}
public void setBookBiz(IBookBiz bookBiz) {
this.bookBiz = bookBiz;
}
@Override
public Book getModel() {
return book;
}
public String addBook() {
bookBiz.addBook(book);
super.toJsonMessager("新增书本信息成功!", true);
return null;
}
public String querySingleBook() {
Book b = bookBiz.get(book);
super.toJsonData(b, true);
return null;
}
public String queryBookPager() {
PageBean pageBean=new PageBean();
pageBean.setRequest(request);
List<Book> lst = bookBiz.queryBookPage(book, pageBean);
super.toJsonData(lst, true);
return null;
}
}
2.biz
IBookBiz
package com.tang.book.biz;
import java.util.List;
import com.tang.base.util.PageBean;
import com.tang.book.entity.Book;
public interface IBookBiz {
public void addBook(Book book);
public void editBook(Book book);
public void delBook(Book book);
public Book get(Book book);
public List<Book> queryBookPage(Book book,PageBean pageBean);
}
BookBizImpl
package com.tang.book.biz;
import java.util.List;
import com.tang.base.biz.BaseBiz;
import com.tang.base.util.PageBean;
import com.tang.book.dao.IBookDao;
import com.tang.book.entity.Book;
public class BookBizImpl extends BaseBiz implements IBookBiz {
//DI:依赖注入,将Dao层注入到Biz层
private IBookDao bookDao;
public IBookDao getBookDao() {
return bookDao;
}
public void setBookDao(IBookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void addBook(Book book) {
bookDao.addBook(book);
}
@Override
public void editBook(Book book) {
bookDao.editBook(book);
}
@Override
public void delBook(Book book) {
bookDao.delBook(book);
}
@Override
public Book get(Book book) {
return bookDao.get(book);
}
@Override
public List<Book> queryBookPage(Book book, PageBean pageBean) {
return bookDao.queryBookPage(book, pageBean);
}
}
3.dao
IBookDao
package com.tang.book.dao;
import java.util.List;
import com.tang.base.util.PageBean;
import com.tang.book.entity.Book;
public interface IBookDao {
public void addBook(Book book);
public void editBook(Book book);
public void delBook(Book book);
public Book get(Book book);
public List<Book> queryBookPage(Book book,PageBean pageBean);
}
BookDaoImpl
package com.tang.book.dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateCallback;
import com.tang.base.dao.BaseDao;
import com.tang.base.util.PageBean;
import com.tang.book.dao.IBookDao;
import com.tang.book.entity.Book;
public class BookDaoImpl extends BaseDao implements IBookDao {
@Override
public void addBook(Book book) {
this.getHibernateTemplate().save(book);
}
@Override
public void editBook(Book book) {
//先查后改
Book b = this.getHibernateTemplate().get(Book.class, book.getBookId());
if(null!=b) {
this.getHibernateTemplate().update(book);
}
}
@Override
public void delBook(Book book) {
//先查后改
Book b = this.getHibernateTemplate().get(Book.class, book.getBookId());
if(null!=b) {
this.getHibernateTemplate().delete(book);
}
}
@Override
public Book get(Book book) {
return this.getHibernateTemplate().get(Book.class, book.getBookId());
}
@Override
public List<Book> queryBookPage(Book book, PageBean pageBean) {
return this.getHibernateTemplate().execute(new HibernateCallback<List<Book>>() {
@Override
public List<Book> doInHibernate(Session session) throws HibernateException {
String hql="from Book";
Query<Book> query = session.createQuery(hql,Book.class);
query.setFirstResult(pageBean.getStartIndex());
query.setMaxResults(pageBean.getRows());
return query.list();
}
});
}
}
BookDaoImplTest
package com.tang.book.dao.impl;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tang.base.util.PageBean;
import com.tang.book.biz.IBookBiz;
import com.tang.book.entity.Book;
public class BookDaoImplTest {
private IBookBiz bookBiz=null;
private Book book=null;
@Before
public void setUp() throws Exception {
ApplicationContext ac=
new ClassPathXmlApplicationContext("classpath:ApplicationContext.xml");
bookBiz=(IBookBiz) ac.getBean("bookBiz");
book=new Book();
}
@Test
public void testAddBook() {
//book.setBookId(7);
book.setBookName("圣经");
book.setBookPrice(200f);
book.setBookType("aa");
bookBiz.addBook(book);
}
@Test
public void testGet() {
book.setBookId(2);
Book b = bookBiz.get(book);
System.out.println(b);
}
@Test
public void testQueryBookPage() {
PageBean pageBean=new PageBean();
List<Book> list = bookBiz.queryBookPage(book, pageBean);
list.forEach(b->{
System.out.println(b);
});
}
}
4.entity
Book
package com.tang.book.entity;
import java.io.Serializable;
public class Book implements Serializable {
private Integer bookId;
private String bookName;
private Float bookPrice;
private String bookType;
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public Float getBookPrice() {
return bookPrice;
}
public void setBookPrice(Float bookPrice) {
this.bookPrice = bookPrice;
}
public String getBookType() {
return bookType;
}
public void setBookType(String bookType) {
this.bookType = bookType;
}
@Override
public String toString() {
return "Book [bookId=" + bookId + ", bookName=" + bookName + ", bookPrice=" + bookPrice + ", bookType="
+ bookType + "]";
}
public Book() {
}
}
Book.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.tang.book.entity.Book" table="book">
<id name="bookId" type="java.lang.Integer" column="bookId">
<generator class="native"></generator>
</id>
<property name="bookName" type="java.lang.String" column="bookName"/>
<property name="bookPrice" type="java.lang.Float" column="bookPrice"/>
<property name="bookType" type="java.lang.String" column="bookType"/>
</class>
</hibernate-mapping>
5.util
EncodingFilter
package com.tang.book.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 中文乱码处理
*
*/
public class EncodingFilter implements Filter {
private String encoding = "UTF-8";// 默认字符集
public EncodingFilter() {
super();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 中文处理必须放到 chain.doFilter(request, response)方法前面
res.setContentType("text/html;charset=" + this.encoding);
if (req.getMethod().equalsIgnoreCase("post")) {
req.setCharacterEncoding(this.encoding);
} else {
Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
Set set = map.keySet();// 取出所有参数名
Iterator it = set.iterator();
while (it.hasNext()) {
String name = (String) it.next();
String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
for (int i = 0; i < values.length; i++) {
values[i] = new String(values[i].getBytes("ISO-8859-1"),
this.encoding);
}
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
if (null != s && !s.trim().equals("")) {
this.encoding = s.trim();
}
}
}
整合案例演示
1 entity
*.hbm.xml
2 dao
IXxxDAO
XxxDAOImpl(继承HibernateDaoSupport类,方便注入HibernateTemplate)
applicationContext-Xxx.xml
3 biz
IXxxBiz
XxxBizImpl
applicationContext-Xxx.xml
4 test(junit4)
5 action
将action配置到applicationContext-Xxx.xml,
注:必须为多例模式(重要)
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<import resource="applicationContext-hibernate.xml"/>
<import resource="ApplicationgContex-book.xml"/>
</beans>
ApplicationgContex-book.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 注册BookDao -->
<bean id="bookDao"
class="com.tang.book.dao.impl.BookDaoImpl"
parent="baseDao">
</bean>
<!-- 注册BookBiz -->
<bean id="bookBiz"
class="com.tang.book.biz.BookBizImpl"
parent="baseBiz">
<property name="bookDao" ref="bookDao"/>
</bean>
<!-- 注册BookAction -->
<bean id="bookAction"
class="com.tang.book.action.BookAction"
parent="baseAction">
<property name="bookBiz" ref="bookBiz"></property>
</bean>
</beans>
struts.xml配置注意事项:
1)
<!-- 将action创建交由spring容器来管理 -->
<constant name="struts.objectFactory" value="spring"></constant>
2)struts-Xxx.xml文件中的action的class属性类型填写spring中的id。
struts-base.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<!-- 开启开发者模式 -->
<constant name="struts.devMode" value="true"></constant>
<!-- 开启自动加载配置文件 -->
<constant name="struts.configuration.xml.reload" value="true"></constant>
<!-- 将action的创建交由Spring框架管理 -->
<constant name="struts.objectFactory" value="spring"></constant>
<!--
name:包名
extends:继承
abstract:是否是抽象类
namespace:命名空间
-->
<package name="struts-base" extends="struts-default" abstract="true" >
<global-allowed-methods>regex:.*</global-allowed-methods>
</package>
</struts>
struts-book.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="struts-book" extends="struts-base" >
<action name="bookAction_*"
method="{1}"
class="bookAction"
>
<result name="success" type=""></result>
</action>
</package>
</struts>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<include file="struts-base.xml"></include>
<include file="struts-book.xml"></include>
</struts>
web.xml配置
1 Spring上下文ApplicationContext.xml的加载
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
2 启动Web容器时,自动装配ApplicationContext.xml的配置信息
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3 中文乱码过滤器
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
4 其他配置
4.1 防止内存泄露、缓存清除监听器
<listener>
<listener-class>
org.springframework.web.util.IntrospectorCleanupListener
</listener-class>
</listener>
4.2 用于支持3种Bean的作用域:request,session和globalSession
<listener>
<listener-class> org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
4.3 把session的关闭延迟到jsp页面显示之后,请配在struts2上面
<filter>
<filter-name>OpenSessionInView</filter-name>
<filter-class> org.springframework.orm.hibernate5.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
5 Struts2核心过滤器
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<!-- Spring上下文ApplicationContext.xml的加载 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ApplicationContext.xml</param-value>
</context-param>
<!-- 启动Web容器时,自动装配ApplicationContext.xml的配置信息 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 中文乱码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.tang.book.util.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 5.4.1 防止内存泄露、缓存清除监听器 -->
<listener>
<listener-class>
org.springframework.web.util.IntrospectorCleanupListener
</listener-class>
</listener>
<!-- 5.4.2 用于支持3种Bean的作用域:request,session和globalSession -->
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<!-- 5.4.3 把session的关闭延迟到jsp页面显示之后,请配在struts2上面 -->
<filter>
<filter-name>OpenSessionInView</filter-name>
<filter-class>
org.springframework.orm.hibernate5.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Struts2核心过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
</web-app>