首页 > 其他 > 详细

SSH整合

时间:2019-08-27 10:36:21      阅读:49      评论:0      收藏:0      [点我收藏+]

SSH是 struts+spring+hibernate的一个集成框架,是目前比较流行的一种Web应用程序开源框架。

SSH的整合思路

1、导入所需要的pom依赖
2、几大框架的配置文件(web.xml/struts.xml、hibernate的配置、spring的配置)
3、spring与hibernate整合桥接的配置文件替换掉了hibernate.cfg.xml
spring-hibernate.xml(难点)
注册数据库连接信息文件
配置数据库连接池(新的知识点)
配置sessionfactory
配置声明式事务(aop)
com.liuwenwu.base.xxxBiz
com.liuwenwu.book.xxxBiz
com.liuwenwu.book.yyyBiz
com.liuwenwu.*.*Biz

配置Base模块

UserDao
private Session session;

add
session
edit
del

<bean id="sesion" class="....">

<bean id="userDao" class="com.zking.dao.UserDao">
<property name="session‘ ref="session"></property>
</bean>
4、配置struts.xml
5、做测试

导入所需的pom依赖 不要一次性导入太多,网不好是容易下不全

pom.xml

  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3   <modelVersion>4.0.0</modelVersion>
  4   <groupId>com.lww</groupId>
  5   <artifactId>T224_SSH</artifactId>
  6   <packaging>war</packaging>
  7   <version>0.0.1-SNAPSHOT</version>
  8   <name>T224_SSH Maven Webapp</name>
  9   <url>http://maven.apache.org</url>
 10   <properties>
 11         <hibernate.version>5.2.12.Final</hibernate.version>
 12         <mysql.version>5.1.44</mysql.version>
 13         <spring.version>5.0.1.RELEASE</spring.version>
 14         <struts2.version>2.5.13</struts2.version>
 15         <slf4j.version>1.7.7</slf4j.version>
 16         <log4j2.version>2.9.1</log4j2.version>
 17         <disruptor.version>3.2.0</disruptor.version>
 18         <junit.version>4.12</junit.version>
 19         <javax.servlet.version>4.0.0</javax.servlet.version>
 20         <jstl.version>1.2</jstl.version>
 21         <standard.version>1.1.2</standard.version>
 22         <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version>
 23     </properties>
 24   
 25   <dependencies>
 26    <!-- 1、导入hibernate依赖 -->
 27            <!-- 核心包 -->
 28         <dependency>
 29             <groupId>org.hibernate</groupId>
 30             <artifactId>hibernate-core</artifactId>
 31             <version>${hibernate.version}</version>
 32         </dependency>
 33         <!-- 桥接包 -->
 34         <dependency>
 35             <groupId>org.hibernate</groupId>
 36             <artifactId>hibernate-c3p0</artifactId>
 37             <version>${hibernate.version}</version>
 38         </dependency>
 39         <!-- 缓存的桥接包 -->
 40         <dependency>
 41             <groupId>org.hibernate</groupId>
 42             <artifactId>hibernate-ehcache</artifactId>
 43             <version>${hibernate.version}</version>
 44         </dependency>
 45         <!-- 数据库驱动包 -->
 46         <dependency>
 47             <groupId>mysql</groupId>
 48             <artifactId>mysql-connector-java</artifactId>
 49             <version>${mysql.version}</version>
 50         </dependency>
 51         
 52         <!-- 2、导入spring依赖 -->
 53         <!-- spring核心包 -->
 54         <dependency>
 55             <groupId>org.springframework</groupId>
 56             <artifactId>spring-context</artifactId>
 57             <version>${spring.version}</version>
 58         </dependency>
 59         <!-- 桥接包 -->
 60         <dependency>
 61             <groupId>org.springframework</groupId>
 62             <artifactId>spring-orm</artifactId>
 63             <version>${spring.version}</version>
 64         </dependency>
 65         <!-- 桥接包  -->
 66         <dependency>
 67             <groupId>org.springframework</groupId>
 68             <artifactId>spring-web</artifactId>
 69             <version>${spring.version}</version>
 70         </dependency>
 71         <!-- spring aop -->
 72         <dependency>
 73             <groupId>org.springframework</groupId>
 74             <artifactId>spring-aspects</artifactId>
 75             <version>${spring.version}</version>
 76         </dependency>
 77         
 78         <!-- 3、导入struts2依赖 -->
 79         <!-- 核心包 -->
 80         <dependency>
 81             <groupId>org.apache.struts</groupId>
 82             <artifactId>struts2-core</artifactId>
 83             <version>${struts2.version}</version>
 84         </dependency>
 85         <!-- struts2-spring整合包 -->
 86         <dependency>
 87             <groupId>org.apache.struts</groupId>
 88             <artifactId>struts2-spring-plugin</artifactId>
 89             <version>${struts2.version}</version>
 90         </dependency>
 91         
 92         <!-- 4、导入日志系统依赖 -->
 93         <!-- log配置:Log4j2 + Slf4j -->
 94         <!-- slf4j核心包 -->
 95         <dependency>
 96             <groupId>org.slf4j</groupId>
 97             <artifactId>slf4j-api</artifactId>
 98             <version>${slf4j.version}</version>
 99         </dependency>
100         <dependency>
101             <groupId>org.slf4j</groupId>
102             <artifactId>jcl-over-slf4j</artifactId>
103             <version>${slf4j.version}</version>
104             <scope>runtime</scope>
105         </dependency>
106 
107         <!--用于与slf4j保持桥接 -->
108         <dependency>
109             <groupId>org.apache.logging.log4j</groupId>
110             <artifactId>log4j-slf4j-impl</artifactId>
111             <version>${log4j2.version}</version>
112         </dependency>
113 
114         <!--核心log4j2jar包 -->
115         <dependency>
116             <groupId>org.apache.logging.log4j</groupId>
117             <artifactId>log4j-api</artifactId>
118             <version>${log4j2.version}</version>
119         </dependency>
120         <dependency>
121             <groupId>org.apache.logging.log4j</groupId>
122             <artifactId>log4j-core</artifactId>
123             <version>${log4j2.version}</version>
124         </dependency>
125 
126         <!--web工程需要包含log4j-web,非web工程不需要 -->
127         <dependency>
128             <groupId>org.apache.logging.log4j</groupId>
129             <artifactId>log4j-web</artifactId>
130             <version>${log4j2.version}</version>
131             <scope>runtime</scope>
132         </dependency>
133         <!--需要使用log4j2的AsyncLogger需要包含disruptor -->
134         <dependency>
135             <groupId>com.lmax</groupId>
136             <artifactId>disruptor</artifactId>
137             <version>${disruptor.version}</version>
138         </dependency>
139     
140     <!-- 5、other -->
141         <!-- 5.1、junit -->
142         <!-- 测试 -->
143         <dependency>
144             <groupId>junit</groupId>
145             <artifactId>junit</artifactId>
146             <version>${junit.version}</version>
147             <scope>test</scope>
148         </dependency>
149 
150         <!-- 5.2、servlet -->
151         <!-- Tomcat依赖 -->
152         <dependency>
153             <groupId>javax.servlet</groupId>
154             <artifactId>javax.servlet-api</artifactId>
155             <version>${javax.servlet.version}</version>
156             <scope>provided</scope>
157         </dependency>
158 
159         <!-- 5.3、jstl、standard -->
160         <!-- C标签库 -->
161         <dependency>
162             <groupId>jstl</groupId>
163             <artifactId>jstl</artifactId>
164             <version>${jstl.version}</version>
165         </dependency>
166         <dependency>
167             <groupId>taglibs</groupId>
168             <artifactId>standard</artifactId>
169             <version>${standard.version}</version>
170         </dependency>
171 
172         <!-- 5.4、tomcat-jsp-api -->
173         <dependency>
174             <groupId>org.apache.tomcat</groupId>
175             <artifactId>tomcat-jsp-api</artifactId>
176             <version>${tomcat-jsp-api.version}</version>
177         </dependency>
178     
179   </dependencies>
180   <build>
181     <finalName>T224_SSH</finalName>
182     <plugins>
183             <plugin>
184                 <groupId>org.apache.maven.plugins</groupId>
185                 <artifactId>maven-compiler-plugin</artifactId>
186                 <version>3.7.0</version>
187                 <configuration>
188                     <source>1.8</source>
189                     <target>1.8</target>
190                     <encoding>UTF-8</encoding>
191                 </configuration>
192             </plugin>
193         </plugins>
194   </build>
195 </project>

框架所需的配置文件

数据库连接 db.properties

db.username=root
db.password=123
db.driverClass=com.mysql.jdbc.Driver
db.jdbcUrl=jdbc:mysql://localhost:3306/t224?useUnicode=true&characterEncoding=UTF-8&useSSL=true
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

web.xml

 1 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 2          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 4          version="3.1">
 5   <display-name>Archetype Created Web Application</display-name>
 6       <!-- 
 7           spring与web整合需要监听器    spring    ioc   spring-web.jar
 8           整合struts框架,配置strutsPreapareAndExecuteFilter
 9           要处理jsp传递到后台的中文乱码问题 配置过滤器  spring提供的过滤器
10           防止内存溢出配置
11        -->
12       <!-- 1、整合spring -->
13     <context-param>
14         <param-name>contextConfigLocation</param-name>
15         <param-value>classpath:spring-context.xml</param-value>
16     </context-param>
17     <listener>
18         <listener-class>
19             org.springframework.web.context.ContextLoaderListener
20         </listener-class>
21     </listener>
22     <!-- 2、整合struts2 -->
23     <filter>
24         <filter-name>struts2</filter-name>
25         <filter-class>
26             org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
27         </filter-class>
28     </filter>
29     <filter-mapping>
30         <filter-name>struts2</filter-name>
31         <url-pattern>*.action</url-pattern>
32     </filter-mapping>
33 
34     <!-- 3、添加过滤器 -->
35     <filter>
36         <filter-name>encodingFilter</filter-name>
37         <filter-class>
38             org.springframework.web.filter.CharacterEncodingFilter
39         </filter-class>
40         <async-supported>true</async-supported>
41         <init-param>
42             <param-name>encoding</param-name>
43             <param-value>UTF-8</param-value>
44         </init-param>
45     </filter>
46     <filter-mapping>
47         <filter-name>encodingFilter</filter-name>
48         <url-pattern>/*</url-pattern>
49     </filter-mapping>
50       
51 </web-app>

log4j2.xml

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 
  3 <!-- status : 指定log4j本身的打印日志的级别.ALL< Trace < DEBUG < INFO < WARN < ERROR 
  4     < FATAL < OFF。 monitorInterval : 用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s. -->
  5 <Configuration status="WARN" monitorInterval="30">
  6     <Properties>
  7         <!-- 配置日志文件输出目录 ${sys:user.home} -->
  8         <Property name="LOG_HOME">/root/workspace/lucenedemo/logs</Property>
  9         <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/error</property>
 10         <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warn</property>
 11         <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n</property>
 12     </Properties>
 13 
 14     <Appenders>
 15         <!--这个输出控制台的配置 -->
 16         <Console name="Console" target="SYSTEM_OUT">
 17             <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
 18             <ThresholdFilter level="trace" onMatch="ACCEPT"
 19                 onMismatch="DENY" />
 20             <!-- 输出日志的格式 -->
 21             <!-- %d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间 %p : 日志输出格式 %c : logger的名称 
 22                 %m : 日志内容,即 logger.info("message") %n : 换行符 %C : Java类名 %L : 日志输出所在行数 %M 
 23                 : 日志输出所在方法名 hostName : 本地机器名 hostAddress : 本地ip地址 -->
 24             <PatternLayout pattern="${PATTERN}" />
 25         </Console>
 26 
 27         <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
 28         <!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true -->
 29         <File name="log" fileName="logs/test.log" append="false">
 30             <PatternLayout
 31                 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
 32         </File>
 33         <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size, 则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
 34         <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
 35             filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
 36             <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
 37             <ThresholdFilter level="info" onMatch="ACCEPT"
 38                 onMismatch="DENY" />
 39             <PatternLayout
 40                 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
 41             <Policies>
 42                 <!-- 基于时间的滚动策略,interval属性用来指定多久滚动一次,默认是1 hour。 modulate=true用来调整时间:比如现在是早上3am,interval是4,那么第一次滚动是在4am,接着是8am,12am...而不是7am. -->
 43                 <!-- 关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval, 日期格式精确到哪一位,interval也精确到哪一个单位 -->
 44                 <!-- log4j2的按天分日志文件 : info-%d{yyyy-MM-dd}-%i.log -->
 45                 <TimeBasedTriggeringPolicy interval="1"
 46                     modulate="true" />
 47                 <!-- SizeBasedTriggeringPolicy:Policies子节点, 基于指定文件大小的滚动策略,size属性用来定义每个日志文件的大小. -->
 48                 <!-- <SizeBasedTriggeringPolicy size="2 kB" /> -->
 49             </Policies>
 50         </RollingFile>
 51 
 52         <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
 53             filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
 54             <ThresholdFilter level="warn" onMatch="ACCEPT"
 55                 onMismatch="DENY" />
 56             <PatternLayout
 57                 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
 58             <Policies>
 59                 <TimeBasedTriggeringPolicy />
 60                 <SizeBasedTriggeringPolicy size="2 kB" />
 61             </Policies>
 62             <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
 63             <DefaultRolloverStrategy max="20" />
 64         </RollingFile>
 65 
 66         <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
 67             filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
 68             <ThresholdFilter level="error" onMatch="ACCEPT"
 69                 onMismatch="DENY" />
 70             <PatternLayout
 71                 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
 72             <Policies>
 73                 <!-- log4j2的按分钟 分日志文件 : warn-%d{yyyy-MM-dd-HH-mm}-%i.log -->
 74                 <TimeBasedTriggeringPolicy interval="1"
 75                     modulate="true" />
 76                 <!-- <SizeBasedTriggeringPolicy size="10 MB" /> -->
 77             </Policies>
 78         </RollingFile>
 79 
 80     </Appenders>
 81 
 82     <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
 83     <Loggers>
 84         <!--过滤掉spring和mybatis的一些无用的DEBUG信息 -->
 85         <logger name="org.springframework" level="INFO"></logger>
 86         <logger name="org.mybatis" level="INFO"></logger>
 87 
 88         <!-- 第三方日志系统 -->
 89         <logger name="org.springframework" level="ERROR" />
 90         <logger name="org.hibernate" level="ERROR" />
 91         <logger name="org.apache.struts2" level="ERROR" />
 92         <logger name="com.opensymphony.xwork2" level="ERROR" />
 93         <logger name="org.jboss" level="ERROR" />
 94 
 95 
 96         <!-- 配置日志的根节点 -->
 97         <root level="all">
 98             <appender-ref ref="Console" />
 99             <appender-ref ref="RollingFileInfo" />
100             <appender-ref ref="RollingFileWarn" />
101             <appender-ref ref="RollingFileError" />
102         </root>
103 
104     </Loggers>
105 
106 </Configuration>

struts-base.xml

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
 4     "http://struts.apache.org/dtds/struts-2.5.dtd">
 5 <struts>
 6     <constant name="struts.i18n.encoding" value="UTF-8" />
 7     <constant name="struts.devMode" value="true" />
 8     <constant name="struts.configuration.xml.reload" value="true" />
 9     <constant name="struts.i18n.reload" value="true" />
10     <constant name="struts.enable.DynamicMethodInvocation" value="true" />
11 
12     <package name="base" extends="struts-default" abstract="true">
13         <global-allowed-methods>regex:.*</global-allowed-methods>
14     </package>
15 </struts>

 

struts-sy.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="sy" extends="base" namespace="/sy">
    <!-- 这里的class不再是全路径名了,而是spring所管理的Bean的id -->
        <action name="/book_*" class="bookAction" method="{1}">
            
        </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-default.xml"></include>
    <include file="struts-base.xml"></include>
    <include file="struts-sy.xml"></include>
</struts>

 

spring-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"
    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">
    
    <bean id="bookdao" class="com.liuwenwu.book.dao.BookDao" parent="baseDao"></bean>
    <bean id="bookbiz" class="com.liuwenwu.book.biz.impl.BookBizImpl" parent="baseBiz">
        <property name="bookdao" ref="bookdao"></property>
    </bean>
    <bean id="bookAction" class="com.liuwenwu.book.web.BookAction" parent="baseAction">
        <property name="bookbiz" ref="bookbiz"></property>
    </bean>
</beans>

spring-hibernate.xml

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <beans xmlns="http://www.springframework.org/schema/beans"
  3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  4     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
  5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  6         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
  7         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
  8         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
  9     
 10     <!-- 1、注册jdbc相关的配置文件 -->
 11     <!-- 2、配置数据库连接池C3P0 -->
 12     <!-- 注册数据库连接文件db.properties -->
 13     <context:property-placeholder location="classpath:db.properties" />
 14 
 15     <!-- 配置c3p0连接池 -->
 16     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 17         <property name="user" value="${db.username}"></property>
 18         <property name="password" value="${db.password}"></property>
 19         <property name="driverClass" value="${db.driverClass}"></property>
 20         <property name="jdbcUrl" value="${db.jdbcUrl}"></property>
 21 
 22         <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
 23         <property name="initialPoolSize" value="${db.initialPoolSize}"></property>
 24         <!--连接池中保留的最大连接数。Default: 15 -->
 25         <property name="maxPoolSize" value="${db.maxPoolSize}"></property>
 26         <!--连接池中保留的最小连接数。 -->
 27         <property name="minPoolSize" value="${db.minPoolSize}" />
 28         <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
 29         <property name="maxIdleTime" value="${db.maxIdleTime}" />
 30 
 31         <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
 32         <property name="acquireIncrement" value="${db.acquireIncrement}" />
 33 
 34         <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。 
 35             所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 
 36 -->
 37         <property name="maxStatements" value="${db.maxStatements}" />
 38 
 39         <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
 40         <property name="idleConnectionTestPeriod" value="${db.idleConnectionTestPeriod}" />
 41 
 42         <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
 43         <property name="acquireRetryAttempts" value="${db.acquireRetryAttempts}" />
 44 
 45         <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。 
 46             如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->
 47         <property name="breakAfterAcquireFailure" value="${db.breakAfterAcquireFailure}" />
 48 
 49         <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod 
 50             或automaticTestTable 等方法来提升连接测试的性能。Default: false -->
 51         <property name="testConnectionOnCheckout" value="${db.breakAfterAcquireFailure}" />
 52     </bean>
 53 
 54     <!-- 3、配置sessionfactory相关信息 -->
 55     <bean id="sessionFactory"
 56         class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
 57         <!-- 数据源 -->
 58         <property name="dataSource">
 59             <ref bean="dataSource" />
 60         </property>
 61         <!-- hibernate相关属性 -->
 62         <property name="hibernateProperties">
 63             <props>
 64                 <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
 65                 <!--spring与Hibernate集成无法显示sql语句问题,请见集成后hibernate无法显示sql语句.txt -->
 66                 <prop key="hibernate.show_sql">true</prop>
 67                 <prop key="hibernate.format_sql">true</prop>
 68             </props>
 69         </property>
 70         <!-- 实体映射文件 -->
 71         <property name="mappingResources">
 72             <list>
 73                 <value>com/liuwenwu/book/entity/Book.hbm.xml</value>
 74             </list>
 75         </property>
 76     </bean>
 77 
 78     <!-- 4、配置事务 -->
 79     <!--声明式事务配置开始 -->
 80     <!-- 
 81         静态代理:
 82             一个代理对象->一个目标对象
 83             BookProxy(BookBizImpl+myMethodBeforeAdvice)->bookBiz
 84             OrderProxy(OrderBizImpl+myMethodBeforeAdvice2)->    OrderBiz
 85         
 86         动态代理:
 87             一个代理对象->多个目标对象
 88      -->
 89     
 90     <!--1) 开启自动代理 -->
 91     <aop:aspectj-autoproxy />
 92 
 93     <!--2) 事务管理器 -->
 94     <bean id="transactionManager"
 95         class="org.springframework.orm.hibernate5.HibernateTransactionManager">
 96         <property name="sessionFactory" ref="sessionFactory" />
 97     </bean>
 98 
 99     <!--3) 定义事务特性 -->
100     <!-- 下面定义了增删改查的事物规则,意味着只有符合下面命名规则的方法,才会获取到session,以及提交事物 -->
101     <tx:advice id="txAdvice" transaction-manager="transactionManager">
102         <tx:attributes>
103             <tx:method name="add*" propagation="REQUIRED" />
104             <tx:method name="save*" propagation="REQUIRED" />
105             <tx:method name="insert*" propagation="REQUIRED" />
106 
107             <tx:method name="edit*" propagation="REQUIRED" />
108             <tx:method name="update*" propagation="REQUIRED" />
109 
110             <tx:method name="del*" propagation="REQUIRED" />
111             <tx:method name="remove*" propagation="REQUIRED" />
112 
113             <tx:method name="load*" propagation="REQUIRED" read-only="true" />
114             <tx:method name="list*" propagation="REQUIRED" read-only="true" />
115             <tx:method name="select*" propagation="REQUIRED" read-only="true" />
116             <tx:method name="query*" propagation="REQUIRED" read-only="true" />
117 
118             <tx:method name="do*" propagation="REQUIRED" />
119         </tx:attributes>
120     </tx:advice>
121 
122     <!--4) 定义切入点 -->
123     <aop:config>
124         <!-- pointcut属性用来定义一个切入点,分成四个部分理解 [* ][*..][*Biz][.*(..)] -->
125         <!-- A: 返回类型,*表示返回类型不限 -->
126         <!-- B: 包名,*..表示包名不限 -->
127         <!-- C: 类或接口名,*Biz表示类或接口必须以Biz结尾 -->
128         <!-- D: 方法名和参数,*(..)表示方法名不限,参数类型和个数不限 -->
129         <aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*Biz.*(..))" />
130         <!-- 为什么一定要切在biz对应的借口上 -->
131     </aop:config>
132     <!-- 声明式事务配置结束 -->
133 
134     <!-- 5、配置HibernateTemplate  session-->
135     <bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate">
136         <property name="sessionFactory" ref="sessionFactory"></property>
137     </bean>
138     <!-- 6、分模块开发(只配置base模块) -->
139     <bean class="com.liuwenwu.base.entity.BaseEntity" abstract="true" id="baseEntity"></bean>
140     <bean class="com.liuwenwu.base.dao.BaseDao" abstract="true" id="baseDao" >
141         <property name="hibernateTemplate" ref="hibernateTemplate"></property>
142     </bean>
143     <bean class="com.liuwenwu.base.biz.BaseBiz" abstract="true" id="baseBiz"></bean>
144     <bean class="com.liuwenwu.base.web.BaseAction" abstract="true" id="baseAction"></bean>
145     
146 </beans>

spring-context.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"
    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">
    
    <import resource="spring-hibernate.xml"/>
    <import resource="spring-book.xml"/>
</beans>

基础base包

BaseDao

 1 package com.liuwenwu.base.dao;
 2 
 3 import java.io.Serializable;
 4 import java.util.Collection;
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 import org.hibernate.Session;
 9 import org.hibernate.query.Query;
10 import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
11 
12 import com.liuwenwu.base.util.PageBean;
13 
14 public class BaseDao extends HibernateDaoSupport implements Serializable{
15 
16     private static final long serialVersionUID = 5427369434249665701L;
17     
18     public void setParam(Query query,Map<String, Object> map) {
19         if(map == null || map.size() < 1) {
20             return;
21         }
22         Object value = null;
23         for(Map.Entry<String, Object> entry:map.entrySet()) {
24             value = entry.getValue();
25             if(value instanceof Collection) {
26                 query.setParameterList(entry.getKey(), (Collection) value);
27             }else if(value instanceof Object[]) {
28                 query.setParameterList(entry.getKey(), (Object[]) value);
29             }else {
30                 query.setParameter(entry.getKey(), value);
31             }
32         }
33     }
34     
35     public String getCountHql(String hql) {
36         int index = hql.toUpperCase().indexOf("FROM");
37         return "select count(*) "+hql.substring(index);
38     }
39     
40     /**
41      * 
42      * @param hql    已经拼装好的
43      * @param map
44      * @param pageBean
45      * @return
46      */
47     public List executeQuery(Session session, String hql,Map<String, Object> map,PageBean pageBean) {
48         if(pageBean !=null && pageBean.isPagination()) {
49             String countHql = getCountHql(hql);
50             Query countQuery = session.createQuery(countHql);
51             this.setParam(countQuery, map);
52             pageBean.setTotal(countQuery.getSingleResult().toString());
53             
54             Query query = session.createQuery(hql);
55             this.setParam(query, map);
56             query.setFirstResult(pageBean.getStartIndex());
57             query.setMaxResults(pageBean.getRows());
58             List list = query.list();
59             
60             return list;
61         }else {
62             Query query = session.createQuery(hql);
63             this.setParam(query, map);
64             List list = query.list();
65             
66             return list;
67         }    
68     }
69 }

BaseAction

 1 package com.liuwenwu.base.web;
 2 
 3 import java.io.Serializable;
 4 
 5 import javax.servlet.ServletContext;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import javax.servlet.http.HttpSession;
 9 
10 import org.apache.struts2.interceptor.ServletRequestAware;
11 import org.apache.struts2.interceptor.ServletResponseAware;
12 
13 public class BaseAction implements ServletRequestAware, ServletResponseAware,Serializable{
14     private static final long serialVersionUID = -7110462505161900879L;
15     /**
16      * 为了传值使用
17      */
18     protected HttpServletResponse response;
19     protected HttpServletRequest request;
20     protected HttpSession session;
21     protected ServletContext application;
22     
23     /**
24      * 为了配置跳转页面所用
25      */
26     protected final static String SUCCESS = "success";
27     protected final static String FAIL = "fail";
28     protected final static String LIST = "list";
29     protected final static String ADD = "add";
30     protected final static String EDIT = "edit";
31     protected final static String DETAIL = "detail";
32     
33     /**
34      * 具体传值字段    后端向jsp页面传值所用字段
35      */
36     protected Object result;
37     protected Object msg;
38     protected int code;
39 
40     public Object getResult() {
41         return result;
42     }
43 
44     public Object getMsg() {
45         return msg;
46     }
47 
48     public int getCode() {
49         return code;
50     }
51 
52     @Override
53     public void setServletResponse(HttpServletResponse arg0) {
54         this.response = arg0;
55         
56     }
57 
58     @Override
59     public void setServletRequest(HttpServletRequest arg0) {
60         this.request = arg0;
61         this.session = arg0.getSession();
62         this.application = arg0.getServletContext();
63     }
64 
65 }

PageBean

  1 package com.liuwenwu.base.util;
  2 
  3 import java.util.Map;
  4 
  5 import javax.servlet.http.HttpServletRequest;
  6 
  7 
  8 /**
  9  * 分页工具类
 10  *
 11  */
 12 public class PageBean {
 13 
 14     private int page = 1;// 页码
 15 
 16     private int rows = 10;// 页大小
 17 
 18     private int total = 0;// 总记录数
 19 
 20     private boolean pagination = true;// 是否分页
 21     // 获取前台向后台提交的所有参数
 22     private Map<String, String[]> parameterMap;
 23     // 获取上一次访问后台的url
 24     private String url;
 25 
 26     /**
 27      * 初始化pagebean
 28      * 
 29      * @param req
 30      */
 31     public void setRequest(HttpServletRequest req) {
 32         this.setPage(req.getParameter("page"));
 33         this.setRows(req.getParameter("rows"));
 34         // 只有jsp页面上填写pagination=false才是不分页
 35         this.setPagination(!"fasle".equals(req.getParameter("pagination")));
 36         this.setParameterMap(req.getParameterMap());
 37         this.setUrl(req.getRequestURL().toString());
 38     }
 39 
 40     public int getMaxPage() {
 41         return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
 42     }
 43 
 44     public int nextPage() {
 45         return this.page < this.getMaxPage() ? this.page + 1 : this.getMaxPage();
 46     }
 47 
 48     public int previousPage() {
 49         return this.page > 1 ? this.page - 1 : 1;
 50     }
 51 
 52     public PageBean() {
 53         super();
 54     }
 55 
 56     public int getPage() {
 57         return page;
 58     }
 59 
 60     public void setPage(int page) {
 61         this.page = page;
 62     }
 63 
 64     public void setPage(String page) {
 65         this.page = StringUtils.isBlank(page) ? this.page : Integer.valueOf(page);
 66     }
 67 
 68     public int getRows() {
 69         return rows;
 70     }
 71 
 72     public void setRows(int rows) {
 73         this.rows = rows;
 74     }
 75 
 76     public void setRows(String rows) {
 77         this.rows = StringUtils.isBlank(rows) ? this.rows : Integer.valueOf(rows);
 78     }
 79 
 80     public int getTotal() {
 81         return total;
 82     }
 83 
 84     public void setTotal(int total) {
 85         this.total = total;
 86     }
 87 
 88     public void setTotal(String total) {
 89         this.total = Integer.parseInt(total);
 90     }
 91 
 92     public boolean isPagination() {
 93         return pagination;
 94     }
 95 
 96     public void setPagination(boolean pagination) {
 97         this.pagination = pagination;
 98     }
 99 
100     public Map<String, String[]> getParameterMap() {
101         return parameterMap;
102     }
103 
104     public void setParameterMap(Map<String, String[]> parameterMap) {
105         this.parameterMap = parameterMap;
106     }
107 
108     public String getUrl() {
109         return url;
110     }
111 
112     public void setUrl(String url) {
113         this.url = url;
114     }
115 
116     /**
117      * 获得起始记录的下标
118      * 
119      * @return
120      */
121     public int getStartIndex() {
122         return (this.page - 1) * this.rows;
123     }
124 
125     @Override
126     public String toString() {
127         return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
128                 + ", parameterMap=" + parameterMap + ", url=" + url + "]";
129     }
130 
131 }

book包

BookBiz

package com.liuwenwu.book.biz;

import java.util.List;

import com.liuwenwu.book.entity.Book;

public interface BookBiz {
    
    public int add(Book book);
    
    public List<Book> list();  
}

book实体类

 1 package com.liuwenwu.book.entity;
 2 
 3 import com.liuwenwu.base.entity.BaseEntity;
 4 
 5 public class Book extends BaseEntity {
 6 
 7     private static final long serialVersionUID = -3928697492940325170L;
 8     private Integer bid;
 9     private String bname;
10     private Float price;
11     public Integer getBid() {
12         return bid;
13     }
14     public void setBid(Integer bid) {
15         this.bid = bid;
16     }
17     public String getBname() {
18         return bname;
19     }
20     public void setBname(String bname) {
21         this.bname = bname;
22     }
23     public Float getPrice() {
24         return price;
25     }
26     public void setPrice(Float price) {
27         this.price = price;
28     }
29     @Override
30     public String toString() {
31         return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
32     } 
33 }

BookBizImpl

 1 package com.liuwenwu.book.biz.impl;
 2 
 3 import java.util.List;
 4 
 5 import com.liuwenwu.book.biz.BookBiz;
 6 import com.liuwenwu.book.dao.BookDao;
 7 import com.liuwenwu.book.entity.Book;
 8 
 9 /**
10  * 
11  * 为什么一定要切在biz对应的接口上
12  * 
13  * BookBizImpl->MoneyBizImpl
14  *  transfer  转账的方法
15  *      from,to
16  *      this.MoneyDao.update(from) from用户的钱减少
17  *      this.MoneyDao.update(to)   to用户的钱增加
18  *  解释:
19  *      试想一下如果说事物的切面点是切在dao上面,意味着
20  *      Transaction t= session.beginTransaction();
21  *      this.MoneyDao.update(from)
22  *      t.commit();
23  *  
24  *      Transaction t= session.beginTransaction();
25  *      this.MoneyDao.update(to)
26  *      t.commit();
27  *  
28  *      此时调用MoneyBizImpl.transfer方法
29  *      Transaction t= session.beginTransaction();
30  *      this.MoneyDao.update(from)
31  *      t.commit();
32  *  
33  *      此处方法生异常    
34  *  
35  *      Transaction t= session.beginTransaction();
36  *      this.MoneyDao.update(to)
37  *      t.commit();  
38  *  
39  *      由上可知:转账涉及到的两个用户不在一个事物中,如果中途发生异常,回滚的话,不能保证数据的唯一性
40  *      切在biz上面:
41  *      MoneyAction中调用MoneyBizImpl.transfer方法
42   *      Transaction t= session.beginTransaction();
43  *      MoneyBizImpl.transfer(from,to);
44  *          相当于this.MoneyDao.update(to)+this.MoneyDao.update(from)
45  *      t.commit();      
46  * @author ASUS
47  *
48  */
49 public class BookBizImpl implements BookBiz{
50     private BookDao bookdao;
51     
52     
53     public BookDao getBookdao() {
54         return bookdao;
55     }
56 
57     public void setBookdao(BookDao bookdao) {
58         this.bookdao = bookdao;
59     }
60 
61     @Override
62     public int add(Book book) {
63         // TODO Auto-generated method stub
64         return bookdao.add(book);
65     }
66 
67     @Override
68     public List<Book> list() {
69         // TODO Auto-generated method stub
70         return bookdao.list();
71     }
72 }

实体类映射文件配置

Book.hbm.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC 
 3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5 <hibernate-mapping>
 6     <class table="t_mvc_book" name="com.liuwenwu.book.entity.Book">
 7         <id name="bid" type="java.lang.Integer" column="bid">
 8             <generator class="increment"></generator>
 9         </id>
10         
11         <property name="bname" type="java.lang.String" column="bname"></property>
12         <property name="price" type="java.lang.Float" column="price"></property>
13     </class>
14 </hibernate-mapping>

BookAction

 1 package com.liuwenwu.book.web;
 2 
 3 import java.util.List;
 4 
 5 import com.liuwenwu.base.web.BaseAction;
 6 import com.liuwenwu.book.biz.BookBiz;
 7 import com.liuwenwu.book.entity.Book;
 8 import com.opensymphony.xwork2.ModelDriven;
 9 
10 public class BookAction extends BaseAction implements ModelDriven<Book>{
11 //  book是实现了modeldriven接口,那么意味着封装了jsp传递到后台的所有参数,详见struts
12     private Book book=new Book();
13     private static final long serialVersionUID = -5384381948425702641L;
14 
15     private BookBiz bookbiz;
16 
17     public BookBiz getBookbiz() {
18         return bookbiz;
19     }
20 
21     public void setBookbiz(BookBiz bookbiz) {
22         this.bookbiz = bookbiz;
23     }
24     
25     public String add() {
26         this.bookbiz.add(book);
27         return null;    
28     }
29     
30     public String list() {
31         List<Book> list= this.bookbiz.list();
32         for (Book b : list) {
33             System.out.println(b);
34         }
35         return null;    
36     }
37     
38     @Override
39     public Book getModel() {
40         return book;
41     } 
42 }

测试查询:

技术分享图片

新增测试:

技术分享图片

技术分享图片

 

技术分享图片

 

SSH整合

原文:https://www.cnblogs.com/hyfl/p/11416325.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!