SSH框架整合
简介:该文章讲述了SSH框架的整合,其中包含了整合思路的整合步骤,使用Spring+Spring-data-jpa+Hibernate框架。
为何要使用SpringDataJpa+Hibernate,因为Hibernate是Jpa的实现,SpringDataJpa对Jpa接口进行了封装,封装好了一套实现类,这样使用Hibernate作为SpringDataJpa的实现进行整合后就不用手写Hibernate实现类,加快了开发效率,类似于Mybatis的代理方式只需要写接口,并不需要写实现类。
方式一:基于jar包+XML方式的ssh整合。
方式二:基于Maven+注解方式的ssh整合。
当然,项目中普遍采用的是第二种方式,不过第一种方式更加利于我们学习SSH的整合过程。
此文章的另外一个目的就是方便以后搭建项目,可以直接来进行copy。也欢迎大家前来copy啦。
1.基于jar包+XML方式的ssh整合
1.1 所需jar包分析
1.1.1 Struts2所需jar包
1)struts_blank示例项目下的13个包
Asm 是关于字节码操作
Commons-fileupload 关于文件上传
Commons-io 关于 io 流操作工具
Commons-lang 也是一个工具,包含了关于数据与字符串操作
Freemaker 标签库模板文件
Javassist 它也是关于字节码操作,动态代理可以使用它实现(类似于 cglib)
Log4j 关于日志
Ognl 关于 ognl 表达式
Struts2-core xwork-cor struts2 框架底层是使用 xwork
2)struts2与Spring整合需要的插件包
3)如果使用struts的json插件还需要json包(可选)
4)如果需要注解开发还需要converttion插件包(可选xml方式不需要该包)
。
1.1.2 Spring所需jar包
1)Spring核心包
2)AOP开发需要的jar包,如使用aspectj框架则需要多一个
3)Spring 事务管理需要的jar一般必须,如果使用Spring jdbcTemplate则需要导入,jdbc和事务tx相关的jar包。
4)Spring整合Struts2,Hibernate,Junit所需要的包
如果你已经完成导入上述jar包,那么恭喜你,可以继续下一步,创建和配置所需的配置文件
1.2 配置文件分析
1)Struts2的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="" class="" method="">
<result name="" type=""></result>
</action>
</package>
</struts>
2)Spring的配置文件
3)Hibernate的配置文件(整合后可以删除此配置文件,这里涉及到Spring整合Hibernate的两种方式)。
方式一:零障碍整合
hibernate配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 配置关于数据库连接的四个项 driverClass url username password -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernateTest</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<!-- 设置连接提供者 -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- c3p0连接池的配置 -->
<property name="hibernate.c3p0.max_size">20</property> <!-- 最大连接池 -->
<property name="hibernate.c3p0.min_size">5</property> <!-- 最小连接数 -->
<property name="hibernate.c3p0.timeout">120</property> <!-- 超时 -->
<property name="hibernate.c3p0.idle_test_period">3000</property> <!-- 空闲连接 -->
<!-- 可以将向数据库发送的sql显示出来 -->
<property name="hibernate.show_sql">true</property>
<!-- 格式化sql -->
<property name="hibernate.format_sql">true</property>
<!-- hibernate的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 自动创建表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 用于设置事务提交方式 -->
<property name="hibernate.connection.autocommit">false</property>
<!-- 配置hibernate的映射文件所在位置 -->
<mapping class="com.fbc0928.domain.User" />
</session-factory>
</hibernate-configuration>
spring中配置
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>
方式二:spring管理hibernate配置文件,此时不需要hibernate.cfg.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:tx="http://www.springframework.org/schema/tx"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- spring整合hibernate方式二 -->
<!-- 加载properties文件 -->
<context:property-placeholder location="classpath:db.properties" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 加载连接池 -->
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<!-- 以下属性在书写时不能省略hibernate -->
<!-- <props> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.format_sql">true</prop>
</props> -->
<!-- 上述的配置可以简写成以下 -->
<value>
hibernate.show_sql=true
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
hibernate.format_sql=true
</value>
</property>
<!-- 加载hibernate的Xxx.hbm.xml配置文件 -->
<property name="mappingResources">
<list>
<value>com/itheima/domain/User.hbm.xml</value>
</list>
</property>
<!-- <property name="mappingLocations"> <list> <value>classpath:cn/ithiema/domain/User.hbm.xml</value>
</list> </property> <property name="mappingDirectoryLocations"> <list> <value>classpath:cn/itheima/domain</value>
</list> </property> -->
</bean>
<!-- 配置连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 声明式事务管理 -->
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" />
<tx:method name="add"/>
<tx:method name="update"/>
<tx:method name="del"/>
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:pointcut expression="execution(* com.itheima.service.*..*(..))" id="mypointcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut"/>
</aop:config>
<!-- 声明dao -->
<bean id="userDao" class="com.itheima.dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 声明service -->
<bean id="userService" class="com.itheima.service.UserServiceImpl">
<property name="userDao" ref="userDao" />
</bean>
<!-- 配置Action -->
<!-- -->
<bean id="userAction" class="com.itheima.action.UserAction">
<property name="userService" ref="userService"></property>
</bean>
</beans>
4)log4j的配置文件
#
# Hibernate, Relational Persistence for Idiomatic Java
#
# License: GNU Lesser General Public License (LGPL), version 2.1 or later.
# See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
#
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=warn, stdout
#log4j.logger.org.hibernate=info
log4j.logger.org.hibernate=debug
#log4j.logger.org.hibernate.hql.ast.AST=debug
#log4j.logger.org.hibernate.SQL=debug
log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug
log4j.logger.org.hibernate.tool.hbm2ddl=debug
#log4j.logger.org.hibernate.hql=debug
#log4j.logger.org.hibernate.cache=debug
#log4j.logger.org.hibernate.transaction=debug
#log4j.logger.org.hibernate.jdbc=debug
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
5)db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///database
jdbc.username=root
jdbc.password=123456
6)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd"
id="WebApp_ID" version="2.5">
<!-- spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext*.xml</param-value>
</context-param>
<!-- spring核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Struts2核心过滤器 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
1.3 整合思路
1)Struts2的Action交给Spring容器管理
2)Hibernate的c3p0连接池、SessionFactory、及映射配置文件的配置交给容器管理
2.基于Maven+注解方式的ssh整合
该方式是开发中常用的方式,必须掌握,该方式整合有以下优点。
- 使用Maven管理的pom.xml来简化jar包的整理和导入,从而可以简化依赖的管理。
- 使用注解开发可以简化配置文件的配置,此时不再需要struts.xml和XXX.hbm.xml配置文件。只需要spring的配置文件applicationContext.xml以及日志、db.properties等配置文件。
- 与上述过程一致,我们来一起使用Maven,的注解来简化配置吧,你会对Maven爱不释手的。
2.1 使用Maven依赖管理简化Jar包导入过程
<dependencies>
<!-- IOC相关包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!-- AOP相关包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<!-- spring data jpa 数据库持久层 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<!-- 整合Web、ORM、Test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<!-- struts2 框架 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
</dependency>
<!-- hibernate 框架 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
</dependency>
<!-- oracle数据库驱动,需要手动安装 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
</dependency>
<!-- 对象转为json 工具包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!-- 日志框架 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<!-- 工具包 -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
<!-- Servlet、JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>9000</port>
</configuration>
</plugin>
</plugins>
</build>
2.2 使用注解进行开发,简化配置文件--注解分析
2.2.1 Struts注解分析
类注解
@ParentPackage("struts-default")
@Namespace("/")
@Controller
@Scope("prototype")
方法注解
@Action(value="访问路径", results={@Results=[@Result={}]})
2.2.2 entity实体类的Jpa注解
@Entity--表示这个类是一个Hibernate实体类、@Table--类与表的映射关系
@Id--表示该属性对应表中主键、@GeneratedValue--主键和生成策略、@Column(name = "C_ID")--该字段对应的表中的字段
@Temporal(TemporalType.TIMESTAMP)--该字段为日期格式
@OneToOne--一对一关系
@OneToMany(mappedBy="多的一方的引用")--放弃外键的维护权、@ManyToOne--多对一关系 @JoinColumn(name = "C_ARCHIVE_ID")--多的一方添加外键列,维护外键
一方写 mappedBy 放弃外键维护、另一方
2.2.3 spring组件注解
@Controller/@RestController、@Service、@Repository
2.3 配置文件
2.3.1 Spring配置文件,注解方式整合后不需要struts.xml和XXX.hbm.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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- 扫描 @Server @Controller @Repository -->
<context:component-scan base-package="cn.itcast"/>
<!-- 加载properties文件 -->
<context:property-placeholder location="classpath:properties/*.properties" />
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 整合JPA配置 -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="cn.itcast.bos.domain" />
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="database" value="ORACLE" />
<property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.query.substitutions" value="true 1, false 0" />
<entry key="hibernate.default_batch_fetch_size" value="16" />
<entry key="hibernate.max_fetch_depth" value="2" />
<entry key="hibernate.generate_statistics" value="true" />
<entry key="hibernate.bytecode.use_reflection_optimizer"
value="true" />
<entry key="hibernate.cache.use_second_level_cache" value="false" />
<entry key="hibernate.cache.use_query_cache" value="false" />
</map>
</property>
</bean>
<!-- JPA事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- 注解管理事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 整合spring data jpa -->
<jpa:repositories base-package="cn.itcast.bos.dao"/>
</beans>
2.3.2 db.properties配置文件
# oracle jdbc properties
jdbc.url=jdbc:oracle:thin:@localhost:1521:XE
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.user=bos
jdbc.password=bos
2.3.3 log4j.properties配置文件
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=info, stdout
2.3.4 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd"
id="WebApp_ID" version="2.5">
<!-- spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext*.xml</param-value>
</context-param>
<!-- spring核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Struts2核心过滤器 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
初始化项目之后,直接启动项目测试,如果不报错表示整合成功,请自行写测试类进行测试!!!