spring_day05_SSH框架整合_XML方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35537301/article/details/81974587

整合前的说明

  • 独立式整合指的是三个框架都使用自己的配置文件

  • 引入式整合指的是hibernate主配置文件中的内容都配置到spring配置文件中

  • 在整合过程中,确保每步都运行成功,然后在继续往下做

  • 整合中使用的案例是客户的保存和列表查询操作

  • 后面的三种整合方式都基于1.2中的环境准备

数据库

create database crm;

/*创建客户表*/
CREATE TABLE `cst_customer` (
  `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
  `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)',
  `cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源',
  `cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业',
  `cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别',
  `cust_address` varchar(128) DEFAULT NULL COMMENT '客户联系地址',
  `cust_phone` varchar(64) DEFAULT NULL COMMENT '客户联系电话',
  PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

 创建web工程

搭建hibernate框架

导入jar包

 创建实体类

import java.io.Serializable;

public class Customer implements Serializable{

	private Long custId;
	private String custName;
	private String custSource;
	private String custIndustry;
	private String custLevel;
	private String custAddress;
	private String custPhone;
	
	
	public Long getCustId() {
		return custId;
	}
	public void setCustId(Long custId) {
		this.custId = custId;
	}
	public String getCustName() {
		return custName;
	}
	public void setCustName(String custName) {
		this.custName = custName;
	}
	public String getCustSource() {
		return custSource;
	}
	public void setCustSource(String custSource) {
		this.custSource = custSource;
	}
	public String getCustIndustry() {
		return custIndustry;
	}
	public void setCustIndustry(String custIndustry) {
		this.custIndustry = custIndustry;
	}
	public String getCustLevel() {
		return custLevel;
	}
	public void setCustLevel(String custLevel) {
		this.custLevel = custLevel;
	}
	public String getCustAddress() {
		return custAddress;
	}
	public void setCustAddress(String custAddress) {
		this.custAddress = custAddress;
	}
	public String getCustPhone() {
		return custPhone;
	}
	public void setCustPhone(String custPhone) {
		this.custPhone = custPhone;
	}
	@Override
	public String toString() {
		return "Customer [custId=" + custId + ", custName=" + custName + ", custSource=" + custSource
				+ ", custIndustry=" + custIndustry + ", custLevel=" + custLevel + ", custAddress=" + custAddress
				+ ", custPhone=" + custPhone + "]";
	}
	
	
}

 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>
		<!-- 必备配置信息 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql:///crm</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		
		<!-- 可选: -->
		<property name="hibernate.hbm2ddl.auto">update</property><!-- 创建数据库的策略 -->
		<property name="hibernate.show_sql">true</property><!-- 显示SQL语句 -->
		<property name="hibernate.format_sql">true</property><!-- 格式化SQL语句 -->
		<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property><!-- 连接池 -->
		
                <!--和spring整合的时候需要删除-->
		<!--把session绑定到当前线程上的配置-->
		<property name="hibernate.current_session_context_class">thread</property>
		<!-- 引入映射文件 -->
		<mapping resource="com/itheima/domain/Customer.hbm.xml"/>
		
	</session-factory>
</hibernate-configuration>

hibernate映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
	
<hibernate-mapping>
	<class name="com.itheima.domain.Customer" table="cst_customer">
		<id name="custId" column="cust_id">
			<generator class="native"/>
		</id>
		
		<property name="custName" column="cust_name"></property>
		<property name="custSource" column="cust_source"></property>
		<property name="custIndustry" column="cust_industry"></property>
		<property name="custLevel" column="cust_level"></property>
		<property name="custAddress" column="cust_address"></property>
		<property name="custPhone" column="cust_phone"></property>
	</class>
</hibernate-mapping>

测试是否成功

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class TestDemo {

	@Test
	public void test01() throws Exception {
		// 1.读取配置文件
		Configuration configure = new Configuration().configure();
		// 2.根据配置文件获取SessionFactory
		SessionFactory factory = configure.buildSessionFactory();
		// 3.根据SessionFactory获取一个Session
		Session s = factory.getCurrentSession();
		// 4.开启事务
		Transaction tx = s.beginTransaction();
		// 5.执行操作
		Query query = s.createQuery("from Customer");
		List list = query.list();
		for (Object o : list) {
			System.out.println(o);
		}
		// 6.提交事务
		tx.commit();
		// 7.释放资源
		factory.close();
	}

}

搭建spring框架

jar包

IOC

AOP

 事务

spring整合Junit

spring整合struts2

spring核心配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
        		http://www.springframework.org/schema/beans/spring-beans.xsd
        		http://www.springframework.org/schema/tx 
        		http://www.springframework.org/schema/tx/spring-tx.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">


	<!-- 创建DAO实例 -->
	<bean id="customerDao" class="com.itheima.dao.impl.CustomerDaoImpl"></bean>

	<!-- 创建service实例 -->
	<bean id="customerService" class="com.itheima.service.impl.CustomerServiceImpl">
		<property name="customerDao" ref="customerDao"></property>
	</bean>
</beans>

dao层

package com.itheima.dao.impl;

import com.itheima.dao.CustomerDao;
import com.itheima.domain.Customer;

public class CustomerDaoImpl implements CustomerDao {

	@Override
	public void saveCustomer(Customer customer) {
		System.out.println("dao方法执行了");
	}

}

service层

package com.itheima.service.impl;

import com.itheima.dao.CustomerDao;
import com.itheima.domain.Customer;
import com.itheima.service.CustomerService;

public class CustomerServiceImpl implements CustomerService {

	private CustomerDao customerDao;

	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}

	@Override
	public void saveCustomer(Customer customer) {
		System.out.println("service添加用户执行力");
		customerDao.saveCustomer(customer);
	}

}

测试是否成功

package com.itheima.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.itheima.domain.Customer;
import com.itheima.service.CustomerService;

public class TestSpring {

	@Test
	public void test() throws Exception {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerService service = (CustomerService) ac.getBean("customerService");
		Customer customer = new Customer();
		service.saveCustomer(customer);
		
	}

}

 搭建struts2框架

 导入jar包

在web.xml文件中,添加struts2拦截器

<?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>ssh</display-name>

	<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>
	
	<!-- struts2核心拦截器 -->
	<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>
	
</web-app>

 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>
	<!-- 开启开发者模式 -->
	<constant name="struts.devMode" value="true"></constant>

	<package name="default" namespace="/" extends="struts-default">
		<action name="*_Customer" class="com.itheima.web.CustomerAction" method="{1}">
			<result name="list_success">/jsp/customer/list.jsp</result>
		</action>

	</package>
</struts>

编写Action动作类

基于XML方式的独立式整合

spring整合hibernate

明确

  • Spring和Hibernate的整合就是spring接管SessionFactory的创建

  • Spring针对Hiberante的操作有一个封装的对象HibernateTemplate

  • 和JdbcTemplate一样,HibernateTemplate也有一个HibernateDaoSupport

  • HibernateTemplate和HibernateDaoSupport都在spring-orm-4.2.4.RELEASE.jar中

  • 我们Dao采用继承HiberanteDaoSupport的方式编写,只能用于XML配置

在spring配置文件中配置SessionFactory

	<!-- 配置数据源(连接池) -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="configLocation" value="classpath:hibernate.cfg.xml" />
	</bean>

改造Dao继承HibernateDaoSupport

package com.itheima.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.itheima.dao.CustomerDao;
import com.itheima.domain.Customer;

public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {

	@Override
	public void saveCustomer(Customer customer) {
		System.out.println("dao方法执行了");
		this.getHibernateTemplate().save(customer);
	}

	@Override
	public List<Customer> findAllCustomer() {
		return (List<Customer>) this.getHibernateTemplate().find("from Customer");
	}

}

 在spring配置文件中给Dao注入SessionFactory

	<!-- 创建DAO实例 -->
	<bean id="customerDao" class="com.itheima.dao.impl.CustomerDaoImpl">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

修改hibernate核心配置文件

去掉Session绑定到当前线程上 

配置Spring的事务

  • 配置事务管理器
<!-- 配置事务管理器 -->
<bean id="transactionManager"
		class="org.springframework.orm.hibernate5.HibernateTransactionManager">
	<!-- 注入SessionFactory -->
	<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
  • 配置事务的通知及通知的属性
<!-- 配置事务的传播行为 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
	<!-- 配置事务的属性 -->
	<tx:attributes>
		<tx:method name="*" read-only="false" propagation="REQUIRED" />
		<tx:method name="find*" read-only="true" propagation="SUPPORTS" />
	</tx:attributes>
</tx:advice>
  • 配置AOP建立切入点表达式和事务通知的关系
<!-- 配置切面 -->
<aop:config>
	<!-- 配置通用切入点表达式 -->
	<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))"
			id="pt1" />
	<!-- 建立事务通知和切入点表达式的对应关系 -->
	<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1" />
</aop:config>
  • 整合hibernate之后的spring核心配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
        		http://www.springframework.org/schema/beans/spring-beans.xsd
        		http://www.springframework.org/schema/tx 
        		http://www.springframework.org/schema/tx/spring-tx.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">


	<!-- 配置数据源(连接池) -->
	<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">
		<!-- 注入SessionFactory -->
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<!-- 配置事务的传播行为 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<!-- 配置事务的属性 -->
		<tx:attributes>
			<tx:method name="*" read-only="false" propagation="REQUIRED" />
			<tx:method name="find*" read-only="true" propagation="SUPPORTS" />
		</tx:attributes>
	</tx:advice>

	<!-- 配置切面 -->
	<aop:config>
		<!-- 配置通用切入点表达式 -->
		<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))"
			id="pt1" />
		<!-- 建立事务通知和切入点表达式的对应关系 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1" />
	</aop:config>


	<!-- 创建DAO实例 -->
	<bean id="customerDao" class="com.itheima.dao.impl.CustomerDaoImpl">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<!-- 创建service实例 -->
	<bean id="customerService" class="com.itheima.service.impl.CustomerServiceImpl">
		<property name="customerDao" ref="customerDao"></property>
	</bean>
</beans>

spring整合struts2

修改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>ssh</display-name>

	<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>

	<!-- struts2核心拦截器 -->
	<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>

	<!-- 配置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>

</web-app>

 在spring配置文件中添加Action配置

	<!-- 配置Action -->
	<bean id="customerAction" class="com.itheima.web.CustomerAction"
		scope="prototype">
		<!-- 注入service -->
		<property name="customerService" ref="customerService"></property>
	</bean>

修改struts.xml文件

 在spring配置文件中配置Action,在struts2配置文件action标签的class属性里写bean的id

<?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>
	<!-- 开启开发者模式 -->
	<constant name="struts.devMode" value="true"></constant>

	<package name="default" namespace="/" extends="struts-default">
		<action name="*_Customer" class="customerAction" method="{1}">
			<result name="list_success">/jsp/customer/list.jsp</result>
		</action>

	</package>
</struts>

Action动作类

package com.itheima.web;

import java.util.List;

import com.itheima.domain.Customer;
import com.itheima.service.CustomerService;
import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction extends ActionSupport {

	private CustomerService customerService;

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	private List<Customer> list;

	public List<Customer> getList() {
		return list;
	}

	public String list() throws Exception {
		list = customerService.findAllCustomer();
		return "list_success";
	}

}

基于XML方式的引入式整合

引入式整合就是把hibernate.cfg.xml中的配置都挪到spring的配置文件中

修改之后的applicationContext.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
        		http://www.springframework.org/schema/beans/spring-beans.xsd
        		http://www.springframework.org/schema/tx 
        		http://www.springframework.org/schema/tx/spring-tx.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">

	<!-- 配置数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="jdbcUrl" value="jdbc:mysql:///crm"></property>
		<property name="user" value="root"></property>
		<property name="password" value="root"></property>
	</bean>

	<!-- 配置数据源(连接池) -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<!-- 1、连接数据库的信息 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 2、hibernate的基本配置 -->
		<property name="hibernateProperties">
			<props>
				<!-- 数据库的方言 -->
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
				<!-- 是否显示sql语句 -->
				<prop key="hibernate.show_sql">true</prop>
				<!-- 是否格式化sql语句 -->
				<prop key="hibernate.format_sql">false</prop>
				<!-- 采用何种方式生成数据库表结构 -->
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<!-- 是spring把sesion绑定到当前线程上的配置 -->
				<prop key="hibernate.current_session_context_class">
					org.springframework.orm.hibernate5.SpringSessionContext
				</prop>
			</props>
		</property>
		
		<!-- 3、映射文件的位置 
			mappingResources:配置映射文件的位置,需要写映射文件名称。
							  并且有几个映射文件,就要写几个<value></value>。
			mappingLocations:配置映射文件的位置,需要写映射文件名称。可以使用通配符。
			mappingDirectoryLocations:配置映射文件的位置,直接写到包的目录即可。
		-->
		<property name="mappingLocations">
			<array>
				<value>classpath:com/itheima/domain/*.hbm.xml</value>
			</array>
		</property>
		
	</bean>

	<!-- 配置事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<!-- 注入SessionFactory -->
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<!-- 配置事务的传播行为 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<!-- 配置事务的属性 -->
		<tx:attributes>
			<tx:method name="*" read-only="false" propagation="REQUIRED" />
			<tx:method name="find*" read-only="true" propagation="SUPPORTS" />
		</tx:attributes>
	</tx:advice>

	<!-- 配置切面 -->
	<aop:config>
		<!-- 配置通用切入点表达式 -->
		<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))"
			id="pt1" />
		<!-- 建立事务通知和切入点表达式的对应关系 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1" />
	</aop:config>


	<!-- 创建DAO实例 -->
	<bean id="customerDao" class="com.itheima.dao.impl.CustomerDaoImpl">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<!-- 创建service实例 -->
	<bean id="customerService" class="com.itheima.service.impl.CustomerServiceImpl">
		<property name="customerDao" ref="customerDao"></property>
	</bean>

	<!-- 配置Action -->
	<bean id="customerAction" class="com.itheima.web.CustomerAction"
		scope="prototype">
		<!-- 注入service -->
		<property name="customerService" ref="customerService" />
	</bean>

</beans>

猜你喜欢

转载自blog.csdn.net/qq_35537301/article/details/81974587
今日推荐