回顾
1、AOP注解方式
编写切面类(包含通知和切入点)
开启自动代理
2、JDBC模版技术
Spring提供模版技术,数据库的操作
以后编写DAO层,都可以继承JdbcDaoSupport类(JDBC模版类)
Spring框架可以整合开源连接池
3、Spring事务管理
Spring框架事务管理需要接口和概述
PlatformTransactionManager接口(平台事务管理接口),不管使用哪种方式管理事务,这个类必须配置
手动编码
声明式事务管理方式,默认使用AOP的技术来增强
XML的方式
注解的方式
SSH三大框架需要的jar包
1、Struts2框架
struts-2.3.24\apps\WEB-INF\lib\*.jar Struts2需要的所有jar包
struts2-spring-plugin-2.3.24.jar Struts2整合Spring的插件包
2、Hibernate框架
hibernate-release-5.0.7.Final\lib\required\*.jar Hibernate框架需要的jar包
slf4j-api-1.6.1.jar 日志接口
slf4j-log4j12-1.7.2.jar 日志实现
mysql-connector-java-5.1.7-bin.jar MySQL的驱动包
3、Spring框架
IOC核心包
AOP核心包
JDBC模版和事务核心包
Spring整合JUnit测试包
Spring整合Sturts2核心包
SSH框架需要的配置文件
1、Struts2框架
在web.xml中配置核心的过滤器
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在src目录下创建struts.xml来配置Action
2、Hibernate框架
在src目录创建Hibernate.cfg.xml配置文件
在JavaBean所在的包下映射的配置iwenjian
3、Spring框架
在web.xml配置整合WEB的监听器
<!-- 配置Spring框架整合监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 加载方式:默认只能加载WEB-INF目录下的配置文件,提供配置方式,加载src目录 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
在src目录下创建applicationContext.xml
在src目录目录下log4j.properties
Spring框架整合Struts2框架
1、导入CRM项目的UI页面,找到添加客户的页面,修改form表单,访问Action
2、编写CustomerAction接受请求,在struts2.xml中完成Action的配置
<package name="crm" extends="struts-default" namespace="/">
<!-- 配置客户的Action -->
<action name="customer_*" class="my.web.action.CustomerAction" method="{1}">
</action>
</package>
3、在Action中获取到service(开发不会用,因为麻烦)
可以通过WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());来获取,但是代码很麻烦
4、Spring整合Sturts2的第一种方式(Action由Struts2框架来创建)
因为导入的struts2-spring-plugin-2.3.24.jar包自带一个配置文件struts-plugin.xml,该配置文件中有如下代码
<constant name="struts.objectFactory" value="spring" />开启一个常量,如果该常量开启,那么下面的常量就可以 使用
struts.objectFactory.spring.autoWire = name 该常量是可以让Action的类来自动装配Bean对象
5、Spring整合Struts2框架的第二种方式(Action由Spring框架来创建)(推荐使用)
把具体的Action类配置在applicationContext.xml的配置文件中,但是struts.xml需要做修改
applicationContext.xml
<bean id="customerAction" class="my.web.action.CustomerAction" scope="prototype"/>
struts.xml中的修改,把全路径修改成ID值
<action name="customer_*" class="customerAction" method="{1}">
第二种方式有2个注意的地方
Spring框架默认生成CustomerAction是单例的,而Struts2框架是多例的,所以需要配置scope="prototype"
CustomerService现在必须自己手动注入了
Spring整合Hibernate框架(带有hibernate.cfg.xml的配置文件)
1、编写CustomerDaoImpl的代码,加入配置并且在CustomerServiceImpl中完成注入
2、编写映射的配置文件,并且在hibernate.cfg.xml的配置文件中引入映射的配置文件
3、在applicationContext.xml的配置文件,配置加载hibernate.cfg.xml的配置
<!-- 编写bean,名称都是固定,加载hibernate.cfg.xml的配置文件 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>
4、在CustomerDaoImpl中想完成数据的添加,Spring框架提供了一个HibernateDaoSupport的工具类,以后DAO都可以继承该类
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao{
public void save(Customer customer) {
System.out.println("持久层:保存客户");
//把数据保存到数据库中
this.getHibernateTemplate().save(customer);
}
}
5、开启事务的配置
先配置事务管理器,现在使用的是Hibernate框架,所以需要使用Hibernate框架的事务管理器
<!-- 先配置平台事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
开启注解事务
<!-- 开启事务的注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
在Service类中添加事务注解
@Transactional
Spring整合Hibernate框架(不带有hibernate.cfg.xml的配置文件)
1、Hibernate配置文件
数据库连接基本参数(4大参数)
Hibernate相关的属性
连接池
映射文件
2、开始进行配置
先配置连接池相关的信息
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///spring_day04"></property>
<property name="user" value="root"></property>
<property name="password" value="123"></property>
</bean>
修改LocalSessionFactoryBean的属性配置,因为没有了hibernate.cfg.xml配置文件,所以需要修改该配置,注入连接池
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
<!-- 先加载连接池 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
继续在LocalSessionFactoryBean中配置,使用hibernateProperties属性继续来配置其他的属性,注意是properties属性文件
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 引入映射的配置文件 -->
<property name="mappingResources">
<list>
<value>my/domain/Customer.hbm.xml</value>
</list>
</property>
Hibernate模版的常用的方法
1、增删改操作
添加
save(Object obj)
修改
update(Object obj)
删除
delete(Object obj)
2、查询的操作
查询一条记录
Object get(Class c,Serializable id)
Object load(Class c,Serializable id)
3、查询多条记录
List find(String hql,Object... args)
延迟加载问题
1、使用延迟加载的时候,在WEB层查询对象的时候会抛出异常
原因是延迟加载还没有发生SQL语句,在业务层session对象就已经销毁了,所以查询到的JavaBean对象已经变成了脱管态对象
一定要先删除低版本的冲突包
2、Spring框架提供了一个过滤器,让session对象在WEB层就创建,在WEB层销毁,只需要配置过滤器即可
需要在Struts2的核心过滤器之前配置
<!-- 解决延迟加载的问题 -->
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
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">
<display-name>day14_ssh1</display-name>
<!-- 配置Spring框架整合监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 解决延迟加载的问题 -->
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</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>
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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/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">
<!-- 编写bean,名称都是固定,加载hibernate.cfg.xml的配置文件 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>
<!-- 先配置平台事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 开启事务的注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 配置客户模块 -->
<!-- 强调:以后配置Action,必须是多例的 -->
<bean id="customerAction" class="my.web.action.CustomerAction" scope="prototype">
<property name="customerService" ref="customerService"/>
</bean>
<bean id="customerService" class="my.service.CustomerServiceImpl">
<property name="customerDao" ref="customerDao"/>
</bean>
<!-- 以后:Dao都需要继承HibernateDaoSupport,注入sessionFactory -->
<bean id="customerDao" class="my.dao.CustomerDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory"></property>
</bean> -->
</beans>
hibernate.cfg.xml
<?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>
<!-- 必须配置 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///spring_day04</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 可选配置 -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置C3P0的连接池 -->
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- 不能配置绑定当前的线程的操作,会报异常,因为交给Spring来管理了 -->
<!-- 映射配置文件 -->
<mapping resource="my/domain/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
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
struts.xml
<?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="crm" extends="struts-default" namespace="/">
<!-- 由Struts2框架自己来管理Action -->
<!-- <action name="customer_*" class="my.web.action.CustomerAction" method="{1}"> -->
<!-- 配置客户的Action,如果action由spring框架来管理,class标签上只需要编写ID值就行 -->
<action name="customer_*" class="my.web.action.CustomerAction" method="{1}">
</action>
</package>
</struts>
Action
/**
* 客户的控制层
* @author Administrator
*
*/
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
private static final long serialVersionUID = 5420567636614077045L;
//需要手动new 和返回对象
private Customer customer = new Customer();
public Customer getModel() {
return customer;
}
//提供service的成员属性,提供set方法
private CustomerService customerService;
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
/**
* 保存客户的方法
* @return
*/
public String add(){
System.out.println("web层:保存");
/*//web工厂
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
CustomerService service = (CustomerService) context.getBean("customerService");
// System.out.println(customer);*/
customerService.save(customer);
return NONE;
}
}
Hibernate模版类基本用法
/**
* Hibernate模版类的简单方法
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo1 {
private CustomerService customerService;
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
@Test
public void run1(){
Customer customer = new Customer();
customer.setCust_id(1L);
customer.setCust_name("笑话");
customerService.update(customer);
}
}
不加hibernate.cfg.xml的applicationContext.xml
<!-- 先配置C3P0的连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///spring_day04"></property>
<property name="user" value="root"></property>
<property name="password" value="123"></property>
</bean>
<!-- LocalSessionFactoryBean加载配置文件 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
<!-- 先加载连接池 -->
<property name="dataSource" ref="dataSource"></property>
<!--加载方言,加载可选-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 引入映射的配置文件 -->
<property name="mappingResources">
<list>
<value>my/domain/Customer.hbm.xml</value>
</list>
</property>
</bean>
<!-- 先配置平台事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 开启事务的注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 配置客户模块 -->
<!-- 强调:以后配置Action,必须是多例的 -->
<bean id="customerAction" class="my.web.action.CustomerAction" scope="prototype">
<property name="customerService" ref="customerService"/>
</bean>
<bean id="customerService" class="my.service.CustomerServiceImpl">
<property name="customerDao" ref="customerDao"/>
</bean>
<!-- 以后:Dao都需要继承HibernateDaoSupport,注入sessionFactory -->
<bean id="customerDao" class="my.dao.CustomerDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory"></property>
</bean> -->
</beans>
dao
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao{
public void save(Customer customer) {
System.out.println("持久层:保存客户");
//把数据保存到数据库中
this.getHibernateTemplate().save(customer);
}
@Override
public void update(Customer customer) {
this.getHibernateTemplate().update(customer);
}
/**
* 通过主键,查询
*/
@Override
public Customer getById(Long id) {
return this.getHibernateTemplate().get(Customer.class,id);
}
/**
* 查询所有
*/
@Override
public List<Customer> findAll() {
List<Customer> list = (List<Customer>) this.getHibernateTemplate().find("from Customer");
return list;
}
/**
* 查询所有的数据,使用QBC的查询
*/
@Override
public List<Customer> findAllByQBC() {
//离线查询 不是session创建的是自己创建的
DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
//设置查询条件
List<Customer> list = (List<Customer>) this.getHibernateTemplate().findByCriteria(criteria);
return list;
}
/**
* 延时加载
*/
public Customer loadById(Long id) {
return this.getHibernateTemplate().load(Customer.class, id);
}
}
service
@Transactional
public class CustomerServiceImpl implements CustomerService {
private CustomerDao customerDao;
public void setCustomerDao(CustomerDao customerDao) {
this.customerDao = customerDao;
}
/**
* 保存客户
*/
@Override
public void save(Customer customer) {
System.out.println("业务层:保存客户");
customerDao.save(customer);
}
@Override
public void update(Customer customer) {
customerDao.update(customer);
}
@Override
public Customer query(Long id) {
return customerDao.getById(id);
}
@Override
public List<Customer> findAll() {
return customerDao.findAll();
}
@Override
public List<Customer> findAllByQBC() {
return customerDao.findAllByQBC();
}
@Override
public Customer loadById(long l) {
return customerDao.loadById(l);
}
}
action
/**
* 客户的控制层
* @author Administrator
*
*/
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
private static final long serialVersionUID = 5420567636614077045L;
//需要手动new 和返回对象
private Customer customer = new Customer();
public Customer getModel() {
return customer;
}
//提供service的成员属性,提供set方法
private CustomerService customerService;
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
/**
* 保存客户的方法
* @return
*/
public String add(){
System.out.println("web层:保存");
/*//web工厂
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
CustomerService service = (CustomerService) context.getBean("customerService");
// System.out.println(customer);*/
customerService.save(customer);
return NONE;
}
/**
* 延时加载的问题
* @return
*/
public String loadById(){
Customer c = customerService.loadById(5L);
//打印客户的名称
System.out.println(c.getCust_name());
return NONE;
}
}
Demo1
/**
* Hibernate模版类的简单方法
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo1 {
@Resource(name="customerService")
private CustomerService customerService;
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
@Test
public void run1(){
Customer customer = new Customer();
// customer.setCust_id(6L);
customer.setCust_name("笑话");
System.out.println(customer);
customerService.save(customer);
}
/**
* 查询某个客户
*/
@Test
public void run2(){
Customer customer = customerService.query(1L);
System.out.println(customer);
}
/**
* 查询所有客户
*/
@Test
public void run3(){
List<Customer> list = customerService.findAll();
System.out.println(list);
}
/**
*
*/
@Test
public void run4(){
List<Customer> list = customerService.findAllByQBC();
System.out.println(list);
}
}