SSH集成
1、创建maven项目并导入pom依赖
pom.xml
注: 建议分步骤导入,以免在导入的时候导致jar包下载出现问题
1 <project xmlns="http://maven.apache.org/POM/4.0.0" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 <groupId>com.yuan</groupId> 6 <artifactId>T226_SSH</artifactId> 7 <packaging>war</packaging> 8 <version>0.0.1-SNAPSHOT</version> 9 <name>T226_SSH Maven Webapp</name> 10 <url>http://maven.apache.org</url> 11 <properties> 12 <hibernate.version>5.2.12.Final</hibernate.version> 13 <mysql.version>5.1.44</mysql.version> 14 <spring.version>5.0.1.RELEASE</spring.version> 15 <struts2.version>2.5.13</struts2.version> 16 <slf4j.version>1.7.7</slf4j.version> 17 <log4j2.version>2.9.1</log4j2.version> 18 <disruptor.version>3.2.0</disruptor.version> 19 <junit.version>4.12</junit.version> 20 <javax.servlet.version>4.0.0</javax.servlet.version> 21 <jstl.version>1.2</jstl.version> 22 <standard.version>1.1.2</standard.version> 23 <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version> 24 </properties> 25 <dependencies> 26 <!-- 1、导入hibernate依赖 --> 27 <dependency> 28 <groupId>org.hibernate</groupId> 29 <artifactId>hibernate-core</artifactId> 30 <version>${hibernate.version}</version> 31 </dependency> 32 <dependency> 33 <groupId>org.hibernate</groupId> 34 <artifactId>hibernate-c3p0</artifactId> 35 <version>${hibernate.version}</version> 36 </dependency> 37 <dependency> 38 <groupId>org.hibernate</groupId> 39 <artifactId>hibernate-ehcache</artifactId> 40 <version>${hibernate.version}</version> 41 </dependency> 42 <dependency> 43 <groupId>mysql</groupId> 44 <artifactId>mysql-connector-java</artifactId> 45 <version>${mysql.version}</version> 46 </dependency> 47 48 <!-- 2、导入spring依赖 --> 49 <dependency> 50 <groupId>org.springframework</groupId> 51 <artifactId>spring-context</artifactId> 52 <version>${spring.version}</version> 53 </dependency> 54 <dependency> 55 <groupId>org.springframework</groupId> 56 <artifactId>spring-orm</artifactId> 57 <version>${spring.version}</version> 58 </dependency> 59 <dependency> 60 <groupId>org.springframework</groupId> 61 <artifactId>spring-web</artifactId> 62 <version>${spring.version}</version> 63 </dependency> 64 <dependency> 65 <groupId>org.springframework</groupId> 66 <artifactId>spring-aspects</artifactId> 67 <version>${spring.version}</version> 68 </dependency> 69 70 <!-- 3、导入struts2依赖 --> 71 <dependency> 72 <groupId>org.apache.struts</groupId> 73 <artifactId>struts2-core</artifactId> 74 <version>${struts2.version}</version> 75 </dependency> 76 <dependency> 77 <groupId>org.apache.struts</groupId> 78 <artifactId>struts2-spring-plugin</artifactId> 79 <version>${struts2.version}</version> 80 </dependency> 81 82 83 <!-- 4、导入日志系统依赖 --> 84 <!-- log配置:Log4j2 + Slf4j --> 85 <!-- slf4j核心包 --> 86 <dependency> 87 <groupId>org.slf4j</groupId> 88 <artifactId>slf4j-api</artifactId> 89 <version>${slf4j.version}</version> 90 </dependency> 91 <dependency> 92 <groupId>org.slf4j</groupId> 93 <artifactId>jcl-over-slf4j</artifactId> 94 <version>${slf4j.version}</version> 95 <scope>runtime</scope> 96 </dependency> 97 98 <!--用于与slf4j保持桥接 --> 99 <dependency> 100 <groupId>org.apache.logging.log4j</groupId> 101 <artifactId>log4j-slf4j-impl</artifactId> 102 <version>${log4j2.version}</version> 103 </dependency> 104 105 <!--核心log4j2jar包 --> 106 <dependency> 107 <groupId>org.apache.logging.log4j</groupId> 108 <artifactId>log4j-api</artifactId> 109 <version>${log4j2.version}</version> 110 </dependency> 111 <dependency> 112 <groupId>org.apache.logging.log4j</groupId> 113 <artifactId>log4j-core</artifactId> 114 <version>${log4j2.version}</version> 115 </dependency> 116 117 <!--web工程需要包含log4j-web,非web工程不需要 --> 118 <dependency> 119 <groupId>org.apache.logging.log4j</groupId> 120 <artifactId>log4j-web</artifactId> 121 <version>${log4j2.version}</version> 122 <scope>runtime</scope> 123 </dependency> 124 <!--需要使用log4j2的AsyncLogger需要包含disruptor --> 125 <dependency> 126 <groupId>com.lmax</groupId> 127 <artifactId>disruptor</artifactId> 128 <version>${disruptor.version}</version> 129 </dependency> 130 131 132 <!-- 5、other --> 133 <!-- 5.1、junit --> 134 <dependency> 135 <groupId>junit</groupId> 136 <artifactId>junit</artifactId> 137 <version>${junit.version}</version> 138 <scope>test</scope> 139 </dependency> 140 141 <!-- 5.2、servlet --> 142 <dependency> 143 <groupId>javax.servlet</groupId> 144 <artifactId>javax.servlet-api</artifactId> 145 <version>${javax.servlet.version}</version> 146 <scope>provided</scope> 147 </dependency> 148 149 <!-- 5.3、jstl、standard --> 150 <dependency> 151 <groupId>jstl</groupId> 152 <artifactId>jstl</artifactId> 153 <version>${jstl.version}</version> 154 </dependency> 155 <dependency> 156 <groupId>taglibs</groupId> 157 <artifactId>standard</artifactId> 158 <version>${standard.version}</version> 159 </dependency> 160 161 <!-- 5.4、tomcat-jsp-api --> 162 <dependency> 163 <groupId>org.apache.tomcat</groupId> 164 <artifactId>tomcat-jsp-api</artifactId> 165 <version>${tomcat-jsp-api.version}</version> 166 </dependency> 167 168 169 170 </dependencies> 171 <build> 172 <finalName>T226_SSH</finalName> 173 <plugins> 174 <plugin> 175 <groupId>org.apache.maven.plugins</groupId> 176 <artifactId>maven-compiler-plugin</artifactId> 177 <version>3.7.0</version> 178 <configuration> 179 <source>1.8</source> 180 <target>1.8</target> 181 <encoding>UTF-8</encoding> 182 </configuration> 183 </plugin> 184 </plugins> 185 </build> 186 </project>
2、导入外部xml
2.1数据库连接信息 db.properties
1 db.username=root 2 db.password=123 3 db.driverClass=com.mysql.jdbc.Driver 4 db.jdbcUrl=jdbc:mysql://127.0.0.1:3306/xm_sc?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT 5 db.initialPoolSize=10 6 db.maxPoolSize=20 7 db.minPoolSize=5 8 db.maxIdleTime=60 9 db.acquireIncrement=5 10 db.maxStatements=0 11 db.idleConnectionTestPeriod=60 12 db.acquireRetryAttempts=30 13 db.breakAfterAcquireFailure=true 14 db.testConnectionOnCheckout=false
2.2 导入ehcache.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" 4 updateCheck="false"> 5 <!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存--> 6 <!--path:指定在硬盘上存储对象的路径--> 7 <!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));--> 8 <diskStore path="java.io.tmpdir"/> 9 10 11 <!--defaultCache:默认的管理策略--> 12 <!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断--> 13 <!--maxElementsInMemory:在内存中缓存的element的最大数目--> 14 <!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上--> 15 <!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false--> 16 <!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问--> 17 <!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问--> 18 <!--memoryStoreEvictionPolicy:缓存的3 种清空策略--> 19 <!--FIFO:first in first out (先进先出)--> 20 <!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存--> 21 <!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存--> 22 <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false" 23 timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/> 24 25 26 <!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)--> 27 <cache name="stuCache" eternal="false" maxElementsInMemory="100" 28 overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" 29 timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/> 30 </ehcache>
2.3 导入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>
2.4 spring-book.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" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 8 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 10 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 11 12 <bean class="com.yuan.book.dao.BookDao" parent="baseDao" id="bookDao"></bean> 13 <bean class="com.yuan.book.biz.impl.BookBizImpl" parent="baseBiz" id="bookBiz"> 14 <property name="bookDao" ref="bookDao"></property> 15 </bean> 16 <bean class="com.yuan.book.web.BookAction" parent="baseAction" id="bookAction"> 17 <property name="bookBiz" ref="bookBiz"></property> 18 </bean> 19 20 </beans>
2.5 spring-context.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" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 8 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 10 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 11 12 <import resource="spring-hibernate.xml"/> 13 <import resource="spring-book.xml"/> 14 15 </beans>
2.6 集成hibernate
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" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 8 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 10 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 11 12 <!-- 13 1、注册数据库连接信息文件 14 2、配置连接池 15 3、配置sessionfactory 16 4、配置事务 17 5、配置切面 18 6、配置通用模块 19 --> 20 <!-- 1、注册jdbc相关的配置文件 --> 21 <context:property-placeholder location="classpath:db.properties" /> 22 23 <!-- 配置c3p0连接池 --> 24 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 25 <property name="user" value="${db.username}"></property> 26 <property name="password" value="${db.password}"></property> 27 <property name="driverClass" value="${db.driverClass}"></property> 28 <property name="jdbcUrl" value="${db.jdbcUrl}"></property> 29 30 <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> 31 <property name="initialPoolSize" value="${db.initialPoolSize}"></property> 32 <!--连接池中保留的最大连接数。Default: 15 --> 33 <property name="maxPoolSize" value="${db.maxPoolSize}"></property> 34 <!--连接池中保留的最小连接数。 --> 35 <property name="minPoolSize" value="${db.minPoolSize}" /> 36 <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> 37 <property name="maxIdleTime" value="${db.maxIdleTime}" /> 38 39 <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> 40 <property name="acquireIncrement" value="${db.acquireIncrement}" /> 41 42 <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。 43 所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 44 0 --> 45 <property name="maxStatements" value="${db.maxStatements}" /> 46 47 <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> 48 <property name="idleConnectionTestPeriod" value="${db.idleConnectionTestPeriod}" /> 49 50 <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> 51 <property name="acquireRetryAttempts" value="${db.acquireRetryAttempts}" /> 52 53 <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。 54 如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false --> 55 <property name="breakAfterAcquireFailure" value="${db.breakAfterAcquireFailure}" /> 56 57 <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod 58 或automaticTestTable 等方法来提升连接测试的性能。Default: false --> 59 <property name="testConnectionOnCheckout" value="${db.breakAfterAcquireFailure}" /> 60 </bean> 61 62 <!-- 3、配置sessionfactory相关信息 --> 63 <bean id="sessionFactory" 64 class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> 65 <!-- 数据源 --> 66 <property name="dataSource"> 67 <ref bean="dataSource" /> 68 </property> 69 <!-- hibernate相关属性 --> 70 <property name="hibernateProperties"> 71 <props> 72 <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop> 73 <!--spring与Hibernate集成无法显示sql语句问题,请见集成后hibernate无法显示sql语句.txt --> 74 <prop key="hibernate.show_sql">true</prop> 75 <prop key="hibernate.format_sql">true</prop> 76 </props> 77 </property> 78 <!-- 实体映射文件 --> 79 <property name="mappingResources"> 80 <list> 81 <value>com/yuan/book/entity/book.hbm.xml</value> 82 </list> 83 </property> 84 </bean> 85 86 <!-- 4、配置事务 --> 87 <!--声明式事务配置开始 --> 88 <!-- 89 静态代理: 90 一个代理对象->一个目标对象 91 BookProxy(BookBizImpl+myMethodBeforeAdvice)->bookBiz 92 OrderProxy(OrderBizImpl+myMethodBeforeAdvice2)-> OrderBiz 93 94 动态代理: 95 一个代理对象->多个目标对象 96 --> 97 98 <!--1) 开启自动代理 --> 99 <aop:aspectj-autoproxy /> 100 101 <!--2) 事务管理器 --> 102 <bean id="transactionManager" 103 class="org.springframework.orm.hibernate5.HibernateTransactionManager"> 104 <property name="sessionFactory" ref="sessionFactory" /> 105 </bean> 106 107 <!--3) 定义事务特性 --> 108 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 109 <tx:attributes> 110 <tx:method name="add*" propagation="REQUIRED" /> 111 <tx:method name="save*" propagation="REQUIRED" /> 112 <tx:method name="insert*" propagation="REQUIRED" /> 113 114 <tx:method name="edit*" propagation="REQUIRED" /> 115 <tx:method name="update*" propagation="REQUIRED" /> 116 117 <tx:method name="del*" propagation="REQUIRED" /> 118 <tx:method name="remove*" propagation="REQUIRED" /> 119 120 <tx:method name="load*" propagation="REQUIRED" read-only="true" /> 121 <tx:method name="list*" propagation="REQUIRED" read-only="true" /> 122 <tx:method name="select*" propagation="REQUIRED" read-only="true" /> 123 <tx:method name="query*" propagation="REQUIRED" read-only="true" /> 124 125 <tx:method name="do*" propagation="REQUIRED" /> 126 </tx:attributes> 127 </tx:advice> 128 129 <!--4) 定义切入点 --> 130 <aop:config> 131 <!-- pointcut属性用来定义一个切入点,分成四个部分理解 [* ][*..][*Biz][.*(..)] --> 132 <!-- A: 返回类型,*表示返回类型不限 --> 133 <!-- B: 包名,*..表示包名不限 --> 134 <!-- C: 类或接口名,*Biz表示类或接口必须以Biz结尾 --> 135 <!-- D: 方法名和参数,*(..)表示方法名不限,参数类型和个数不限 --> 136 <aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*Biz.*(..))" /> 137 </aop:config> 138 <!-- 声明式事务配置结束 --> 139 140 <!-- 5、配置HibernateTemplate 可以看成session --> 141 <bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate"> 142 <property name="sessionFactory" ref="sessionFactory"></property> 143 </bean> 144 <!-- 6、分模块开发(只配置base模块) --> 145 <bean class="com.yuan.base.entity.BaseEntity" abstract="true" id="baseEntity"></bean> 146 <bean class="com.yuan.base.dao.BaseDao" abstract="true" id="baseDao" > 147 <property name="hibernateTemplate" ref="hibernateTemplate"></property> 148 </bean> 149 <bean class="com.yuan.base.biz.BaseBiz" abstract="true" id="baseBiz"></bean> 150 <bean class="com.yuan.base.web.BaseAction" abstract="true" id="baseAction"></bean> 151 152 </beans>
2.7 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>
2.8 struts-book.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 <package name="book" extends="base" namespace="/book"> 7 <action name="/book_*" class="bookAction" method="{1}"> 8 </action> 9 </package> 10 </struts>
2.9 struts.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 <include file="struts-default.xml"></include> 7 <include file="struts-base.xml"></include> 8 <include file="struts-book.xml"></include> 9 </struts>
最后一个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 <!-- 1、整合spring --> 8 <context-param> 9 <param-name>contextConfigLocation</param-name> 10 <param-value>classpath:spring-context.xml</param-value> 11 </context-param> 12 <listener> 13 <listener-class> 14 org.springframework.web.context.ContextLoaderListener 15 </listener-class> 16 </listener> 17 <!-- 2、整合struts2 --> 18 <filter> 19 <filter-name>struts2</filter-name> 20 <filter-class> 21 org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter 22 </filter-class> 23 </filter> 24 <filter-mapping> 25 <filter-name>struts2</filter-name> 26 <url-pattern>*.action</url-pattern> 27 </filter-mapping> 28 29 <!-- 3、添加过滤器 --> 30 <filter> 31 <filter-name>encodingFilter</filter-name> 32 <filter-class> 33 org.springframework.web.filter.CharacterEncodingFilter 34 </filter-class> 35 <async-supported>true</async-supported> 36 <init-param> 37 <param-name>encoding</param-name> 38 <param-value>UTF-8</param-value> 39 </init-param> 40 </filter> 41 <filter-mapping> 42 <filter-name>encodingFilter</filter-name> 43 <url-pattern>/*</url-pattern> 44 </filter-mapping> 45 46 </web-app>
3. 程序代码的分层
3.1 base模块
3.1.1 biz接口--BaseBiz
只需 创建就可以了,后期不需要进行任何操作
package com.yuan.base.biz; public interface BaseBiz { }
3.1.2 dao层--BaseDao
1 package com.yuan.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.yuan.base.util.PageBean; 13 14 public class BaseDao extends HibernateDaoSupport implements Serializable { 15 16 // public int add() { 17 // return getHibernateTemplate().save(entity); 18 // } 19 20 public void setParam(Query query, Map<String, Object> map) { 21 if (map == null || map.size() < 1) { 22 return; 23 } 24 Object value = null; 25 for (Map.Entry<String, Object> entry : map.entrySet()) { 26 value = entry.getValue(); 27 if (value instanceof Collection) { 28 query.setParameterList(entry.getKey(), (Collection) value); 29 } else if (value instanceof Object[]) { 30 query.setParameterList(entry.getKey(), (Object[]) value); 31 } else { 32 query.setParameter(entry.getKey(), value); 33 } 34 } 35 } 36 37 public String getCountHql(String hql) { 38 int index = hql.toUpperCase().indexOf("FROM"); 39 return "select count(*) " + hql.substring(index); 40 } 41 42 /** 43 * 44 * @param hql 45 * 已经拼装好的 46 * @param map 47 * @param pageBean 48 * @return 49 */ 50 public List executeQuery(Session session, String hql, Map<String, Object> map, PageBean pageBean) { 51 if (pageBean != null && pageBean.isPagination()) { 52 String countHql = getCountHql(hql); 53 Query countQuery = session.createQuery(countHql); 54 this.setParam(countQuery, map); 55 pageBean.setTotal(countQuery.getSingleResult().toString()); 56 57 Query query = session.createQuery(hql); 58 this.setParam(query, map); 59 query.setFirstResult(pageBean.getStartIndex()); 60 query.setMaxResults(pageBean.getRows()); 61 List list = query.list(); 62 63 return list; 64 } else { 65 Query query = session.createQuery(hql); 66 this.setParam(query, map); 67 List list = query.list(); 68 69 return list; 70 } 71 72 } 73 74 }
3.1.3 实体--BaseEntity
1 package com.yuan.base.entity; 2 3 import java.io.Serializable; 4 5 /** 6 * 这里面存放所有实体类的共性属性 7 * jsp传递到后台的参数 8 * 非数据库与表的映射关系字段属性 9 * @author ly 10 * 11 */ 12 public class BaseEntity implements Serializable { 13 14 15 }
3.1.4 工具类
PageBean
1 package com.yuan.base.util; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 9 10 public class PageBean { 11 12 private int page = 1; 13 14 private int rows = 10; 15 16 private int total = 0; 17 18 private boolean pagination = true; 19 20 private Map<String, String[]> paMap = new HashMap<>(); 21 22 private String url; 23 24 public void setRequest(HttpServletRequest req) { 25 Map<String, String[]> parameterMap = req.getParameterMap(); 26 StringBuffer url = req.getRequestURL(); 27 28 this.setPaMap(req.getParameterMap()); 29 this.setUrl(req.getRequestURL().toString()); 30 31 this.setPage(req.getParameter("page")); 32 } 33 34 35 private void setPage(String page) { 36 this.page = StringUtils.isNotBlank(page) ? Integer.valueOf(page):this.page; 37 38 } 39 40 41 public void setPagination(String pagination) { 42 this.pagination = StringUtils.isNotBlank(pagination) ? !"false".equals(pagination):this.pagination; 43 44 } 45 46 47 public void setRows(String rows) { 48 this.rows = StringUtils.isNotBlank(rows)?Integer.valueOf(rows):this.rows; 49 50 } 51 52 public Map<String, String[]> getPaMap() { 53 return paMap; 54 } 55 56 public void setPaMap(Map<String, String[]> paMap) { 57 this.paMap = paMap; 58 } 59 60 public String getUrl() { 61 return url; 62 } 63 64 public void setUrl(String url) { 65 this.url = url; 66 } 67 68 public PageBean() { 69 super(); 70 } 71 72 public int getPage() { 73 return page; 74 } 75 76 public void setPage(int page) { 77 this.page = page; 78 } 79 80 public int getRows() { 81 return rows; 82 } 83 84 public void setRows(int rows) { 85 this.rows = rows; 86 } 87 88 public int getTotal() { 89 return total; 90 } 91 92 public void setTotal(int total) { 93 this.total = total; 94 } 95 96 public void setTotal(String total) { 97 this.total = Integer.parseInt(total); 98 } 99 100 public boolean isPagination() { 101 return pagination; 102 } 103 104 public void setPagination(boolean pagination) { 105 this.pagination = pagination; 106 } 107 108 109 public int getStartIndex() { 110 return (this.page - 1) * this.rows; 111 } 112 113 @Override 114 public String toString() { 115 return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]"; 116 } 117 118 119 public int getMaxPage() { 120 121 return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows+1; 122 } 123 124 125 public int getNexPage() { 126 127 return this.page < this.getMaxPage() ? this.page+1 : this.page; 128 } 129 130 131 public int getPreviousPage() { 132 133 return this.page > 1 ? this.page-1 : this.page; 134 } 135 136 }
StringUtils
1 package com.yuan.base.util; 2 3 public class StringUtils { 4 // 私有的构造方法,保护此类不能在外部实例化 5 private StringUtils() { 6 } 7 8 /** 9 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false 10 * 11 * @param s 12 * @return 13 */ 14 public static boolean isBlank(String s) { 15 boolean b = false; 16 if (null == s || s.trim().equals("")) { 17 b = true; 18 } 19 return b; 20 } 21 22 /** 23 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false 24 * 25 * @param s 26 * @return 27 */ 28 public static boolean isNotBlank(String s) { 29 return !isBlank(s); 30 } 31 32 }
3.1.5 web层--BaseAction
1 package com.yuan.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 }
3.2 book模块
3.2.1 biz接口--BooKBiz
1 package com.yuan.book.biz; 2 3 import java.util.List; 4 5 import com.yuan.book.entity.Book; 6 7 public interface BookBiz { 8 9 public int add(Book book); 10 11 public void edit(Book book); 12 13 public void del(Book book); 14 15 public List<Book> list(); 16 17 }
3.2.2 biz接口实现类--BookBizImpl
1 package com.yuan.book.biz.impl; 2 3 import java.util.List; 4 5 import com.yuan.book.biz.BookBiz; 6 import com.yuan.book.dao.BookDao; 7 import com.yuan.book.entity.Book; 8 9 10 /** 11 * pointcut="execution(* *..*Biz.*(..))" 12 * 为什么切面要切在biz上面而不能切在dao层上? 13 * 明确切面的作用: 14 * 切面的目的是为了在目标对象的方法定义事务特性(add/del/edit/list) 15 * 给上面所列举的方法开启或提交事务等等 16 * 17 * 举例说明切在biz与切在dao层上的区别 18 * web层: 19 * MoneyAction.transfer(){ 20 * MoneyBiz.transfer(User u1,User u2); 21 * } 22 * biz层: 23 * MoneyBiz.transfer(User u1,User u2){ 24 * MoneyDao.edit(u1); 25 * MoneyDao.edit(u2); 26 * } 27 * 28 * dao层: 29 * MoneyDao.edit(User u) 30 * 31 * 32 * 银行转账的例子 33 * 如果是切在dao层上: 34 * SSH解读程序员所写的代码 35 * biz层: 36 * MoneyBiz.transfer(User u1,User u2){ 37 * Transation t1= session.beginTransation(); 38 * MoneyDao.edit(u1); 39 * t1.commit(); 40 * Transation t2= session.beginTransation(); 41 * MoneyDao.edit(u2); 42 * t2.commit(); 43 * } 44 * 从上面代码可以看出,一个转账功能处于两个事务当中! 45 * 46 * 如果 MoneyDao.edit(u1); 这里发生了异常 47 * MoneyDao.edit(u2); 48 * 49 * 如果切在biz层上: 50 * web层: 51 * MoneyAction.transfer(){ 52 * Transation t= session.beginTransation(); 53 * MoneyDao.edit(u1); 出现异常 54 * MoneyDao.edit(u2); 55 * t.commit(); 56 * } 57 * 58 * 总:如果切在dao层上,一个方法可能会出现多个事务提交, 59 * 在执行到中间位置时出现异常 60 * 会导致后面的还没有开始运行, 61 * 而前面的就已经提交了。 62 * 63 * 如果切在biz层上,只需一个事务提交, 64 * 中间出现异常不会提交事务, 65 * 执行完后再提交事务,方便于事务回滚 66 * 67 * @author ly 68 * 69 */ 70 public class BookBizImpl implements BookBiz { 71 72 private BookDao bookDao; 73 74 public BookDao getBookDao() { 75 return bookDao; 76 } 77 78 public void setBookDao(BookDao bookDao) { 79 this.bookDao = bookDao; 80 } 81 82 @Override 83 public int add(Book book) { 84 return bookDao.add(book); 85 } 86 87 @Override 88 public void edit(Book book) { 89 bookDao.edit(book); 90 } 91 92 @Override 93 public void del(Book book) { 94 bookDao.del(book); 95 } 96 97 @Override 98 public List<Book> list() { 99 return bookDao.list(); 100 } 101 102 }
3.2.3 dao层--BookDao
1 package com.yuan.book.dao; 2 3 import java.util.List; 4 5 import org.hibernate.HibernateException; 6 import org.hibernate.Session; 7 import org.springframework.orm.hibernate5.HibernateCallback; 8 9 import com.yuan.base.dao.BaseDao; 10 import com.yuan.book.entity.Book; 11 12 /** 13 * 注意: 1、必须继承BaseDao,是为了获取到hibernateTemplate 2、方法命名有讲究(一定要符合声明式事务所定义的规则) 14 * 如果不遵守命名规则,那么数据是不会提交到数据库的 3、hibernateTemplate模板在执行查询的时候比较特殊 15 * 16 * @author ly 17 * 18 * 19 */ 20 public class BookDao extends BaseDao { 21 22 public int add(Book book) { 23 return (int) getHibernateTemplate().save(book); 24 } 25 26 public void edit(Book book) { 27 getHibernateTemplate().update(book); 28 } 29 30 public void del(Book book) { 31 getHibernateTemplate().delete(book); 32 } 33 34 public List<Book> list(){ 35 return (List<Book>)getHibernateTemplate().execute(new HibernateCallback<List<Book>>() { 36 37 @Override 38 public List<Book> doInHibernate(Session session) throws HibernateException { 39 return session.createQuery("from Book").list(); 40 } 41 42 }); 43 } 44 45 }
3.2.4 实体
Book
1 package com.yuan.book.entity; 2 3 import java.io.Serializable; 4 import java.util.HashSet; 5 import java.util.Set; 6 7 /** 8 * 一对多,一本书对应多种书本类型 9 * @author ly 10 * 11 */ 12 public class Book implements Serializable{ 13 // book_id int primary key auto_increment, 14 // book_name varchar(50) not null, 15 // price float not null 16 private Integer bookId; 17 private String bookName; 18 private Float price; 19 20 21 public Integer getBookId() { 22 return bookId; 23 } 24 25 public void setBookId(Integer bookId) { 26 this.bookId = bookId; 27 } 28 29 public String getBookName() { 30 return bookName; 31 } 32 33 public void setBookName(String bookName) { 34 this.bookName = bookName; 35 } 36 37 public Float getPrice() { 38 return price; 39 } 40 41 public void setPrice(Float price) { 42 this.price = price; 43 } 44 45 46 @Override 47 public String toString() { 48 return "Book [bookId=" + bookId + ", bookName=" + bookName + ", price=" + price + "]"; 49 } 50 51 public Book(Integer bookId, String bookName) { 52 super(); 53 this.bookId = bookId; 54 this.bookName = bookName; 55 } 56 57 public Book() { 58 super(); 59 } 60 61 62 }
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 7 8 <class table="t_hibernate_book" name="com.yuan.book.entity.Book"> 9 10 11 <id name="bookId" column="book_id" type="java.lang.Integer"> 12 13 <generator class="increment"/> 14 15 </id> 16 17 <property name="bookName" column="book_name" type="java.lang.String"> </property> 18 19 <property name="price" column="price" type="java.lang.Float"> </property> 20 21 <!-- set标签 table:对应的是中间表,没有实体类的,意味着靠两张主表对应的映射文件联合管理数据 name:当前映射文件对应的实体类对应的属性 cascade:级联新增修改,说白了就是当前实体类对应的表删除能否影响到关联表的数据 inberse:中间表的数据维护的权利交给对方 key标签 column:当前表t_hibernate_book_category的主键book_id在中间表的列段bidmany-to-many:column:代表中间表对应的除去当前表t_hibernate_book的非主键的中间列段cidclass:cid对应的类 <set table="t_hibernate_book_category" name="categories" cascade="save-update" inverse="true">one<key column="bid"></key>many<many-to-many column="cid" class="com.jt4.entity.Category"></many-to-many></set> --> 22 23 24 </class> 25 26 </hibernate-mapping>
3.2.5 web层--BookAction
1 package com.yuan.book.web; 2 3 import java.util.List; 4 5 import com.opensymphony.xwork2.ModelDriven; 6 import com.yuan.base.web.BaseAction; 7 import com.yuan.book.biz.BookBiz; 8 import com.yuan.book.entity.Book; 9 10 public class BookAction extends BaseAction implements ModelDriven<Book> { 11 12 private Book book = new Book(); 13 private BookBiz bookBiz; 14 15 @Override 16 public Book getModel() { 17 // TODO Auto-generated method stub 18 return book; 19 } 20 21 public BookBiz getBookBiz() { 22 return bookBiz; 23 } 24 25 public void setBookBiz(BookBiz bookBiz) { 26 this.bookBiz = bookBiz; 27 } 28 29 public String add() { 30 System.out.println(book); 31 this.bookBiz.add(book); 32 return null; 33 } 34 35 public String edit() { 36 System.out.println(book); 37 this.bookBiz.edit(book); 38 return null; 39 } 40 41 public String del() { 42 System.out.println(book); 43 this.bookBiz.del(book); 44 return null; 45 } 46 47 public String list() { 48 List<Book> list2 = this.bookBiz.list(); 49 for (Book b : list2) { 50 System.out.println(b); 51 } 52 return null; 53 } 54 55 56 57 }