Spring之七 整合SSH2

1. 加入 Spring

1) 加入 jar 包

commons-logging-1.1.3.jar

spring-aop.4.0.0.REALESE.jar

spring-aspects-4.0.0.REALESE.jar

spring-beans-4.0.0.REALESE.jar

spring-context-4.0.0.REALESE.jar

spring-core-4.0.0.REALESE.jar

spring-expression-4.0.0.REALESE.jar

spring-jdbc-4.0.0.REALESE.jar

spring-orm-4.0.0.REALESE.jar

spring-tx-4.0.0.REALESE.jar

com.springsource.net.sf.cglib-2.2.0.jar

com.springsource.org.aopalliance-1.0.0.jar

com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

--web项目额外需要的jar包--

spring-web-4.0.0.REALESE.jar

spring-webmvc-4.0.0.REALESE.jar


2) 配置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">
		<context-param>
			<param-name>configLocation</param-name>
			<param-value>applicationContext.xml</param-value>
		</context-param>
		<listener>
			<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
		</listener>
	</web-app>


3)加入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-2.5.xsd
			  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.0.RELEASE.xsd
			  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.0.RELEASE.xsd
			  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.0.RELEASE.xsd
	">
		
	</beans>

2. 加入 Hibernate

1) 加入 jar 包

jboss-transaction-api_1.1_spec-1.0.1.Final.jar

jboss-logging-3.1.0.GA.jar

javassist-3.15.0-GA.jar

hibernate-jpa-2.0-api-1.0.1.Final.jar

hibernate-core-4.2.4.Final.jar

hibernate-commons-annotations-4.0.2.Final.jar

dom4j-1.6.1.jar

antlr-2.7.7.jar


2) 在类路径下加入 hibernate.cfg.xml 文件, 在其中配置 hibernate 的基本属性

	<?xml version="1.0" encoding="UTF-8"?>
	<!DOCTYPE hibernate-configuration PUBLIC
			"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
			"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
	<hibernate-configuration>
		<session-factory>
			<!-- 配置 hibernate 的基本属性 -->
		
			<!-- 方言 -->
			<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
			
			<!-- 是否显示及格式化 SQL -->
			<property name="hibernate.show_sql">true</property>
			<property name="hibernate.format_sql">true</property>
		
			<!-- 生成数据表的策略 -->
			<property name="hibernate.hbm2ddl.auto">update</property>
			
			<!-- 二级缓存相关 -->
			
		</session-factory>
		
	</hibernate-configuration>

3) 建立持久化类, 和其对应的 .hbm.xml 文件

-----------------------  见实例代码  -----------------------------

4) 和 Spring 进行整合

i.  加入 c3p0 和 MySQL 的驱动

① 引用jar包

c3p0-0.9.1.2.jar

mysql-connector-java-5.1.7-bin.jar

mchange-commons-java-0.2.3.4.jar

② db.properties

jdbc.user=root

jdbc.password=123

jdbc.driverClass=com.mysql.jdbc.Driver

jdbc.jdbcUrl=jdbc:mysql:///test

jdbc.initPoolSize=5

jdbc.maxPoolSize=10



ii. 在 Spring 的配置文件中配置

① 导入资源文件

② 配置 C3P0 数据源

③ 配置SessionFactory

④ 声明式事务


<!-- 导入资源文件 -->
		<context:property-placeholder location="classpath:db.properties"/>

		<!-- 配置 C3P0 数据源 -->
		<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
			<property name="user" value="${jdbc.user}"></property>
			<property name="password" value="${jdbc.password}"></property>
			<property name="driverClass" value="${jdbc.driverClass}"></property>
			<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
			
			<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
			<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
		</bean>
		
		<!-- 配置 SessionFactory -->
		<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
			<property name="dataSource" ref="dataSource"></property>
			<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
			<property name="mappingLocations" value="classpath:com/ithings/ssh/entities/*.hbm.xml"></property>
		</bean>
		
		
		
		<!-- 配置 Spring 的声明式事务 -->
		<!-- 1. 配置 hibernate 的事务管理器 -->
		<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
			<property name="sessionFactory" ref="sessionFactory"></property>
		</bean>

		<!-- 2. 配置事务属性 -->
		<tx:advice id="txAdvice" transaction-manager="transactionManager">
			<tx:attributes>
				<tx:method name="get*" read-only="true"/>
				<tx:method name="lastNameIsValid" read-only="true"/>
				<tx:method name="*"/>
			</tx:attributes>
		</tx:advice>
		
		<!-- 3. 配置事务切入点, 再把事务属性和事务切入点关联起来 -->
		<aop:config>
			<aop:pointcut expression="execution(* com.atguigu.ssh.service.*.*(..))" id="txPointcut"/>
			<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
		</aop:config>

3. 整合Struts2

1). 加入 jar 包

asm-3.3.jar

asm-commons-3.3.jar

asm-tree-3.3.jar

commons-fileupload-1.3.jar

commons-io-2.0.1.jar

commons-lang3-3.1.jar

freemarker-2.3.19.jar

log4j-1.2.17.jar

ognl-3.0.6.jar

struts2-core-2.3.15.3.jar

xwork-core-2.3.15.3.jar


2). 在 web.xml 文件中配置 Struts2 的 Filter

     <!-- 配置 Struts2 的 Filter -->
     <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>

3). 加入 Struts2 的配置文件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>
		<constant name="struts.enable.DynamicMethodInvocation" value="false" />
		<constant name="struts.devMode" value="true" />
		<package name="default" namespace="/" extends="struts-default">
				
		</package>
	</struts>

4). 整合 Spring

①. 加入 Struts2 的 Spring 插件的 jar 包
struts2-spring-plugin-2.3.15.3.jar

②. 在 Spring 的配置文件中正常配置 Action, 注意 Action 的 scope 为 prototype

		<bean id="employeeAction" class="com.ithings.ssh.actions.EmployeeAction"
			scope="prototype">
		</bean>
③. 在 Struts2 的配置文件中配置 Action 时, class 属性指向该 Action 在 IOC 中的 id
	<action name="emp-*" class="employeeAction"
        	method="{1}">
            <result name="list">/WEB-INF/views/emp-list.jsp</result>
            <result name="input">/WEB-INF/views/emp-input.jsp</result>
            <result name="success" type="redirect">/emp-list</result>
        </action>


4 部分项目代码


Employee.java

public class Employee {

    private Integer id;
    // 不能被修改
    private String lastName;
    private String email;
    // 从前端传入的是 String 类型, 所以需要注意转换
    private Date birth;
    // 不能被修改
    private Date createTime;
    // 单向 n-1 的关联关系
    private Department department;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", lastName=" + lastName + ", email="
                + email + ", birth=" + birth + ", createTime=" + createTime
                + ", department=" + department + "]";
    }

Employee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2014-7-22 11:21:48 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.ithings.entities.Employee" table="SSH_EMPLOYEE">
        
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        
        <property name="lastName" type="java.lang.String">
            <column name="LAST_NAME" />
        </property>
        
        <property name="email" type="java.lang.String">
            <column name="EMAIL" />
        </property>
        
        <property name="birth" type="java.util.Date">
            <column name="BIRTH" />
        </property>
        
        <property name="createTime" type="java.util.Date">
            <column name="CREATE_TIME" />
        </property>
        
        <!-- 映射单向 n-1 的关联关系 -->
        <many-to-one name="department" class="com.ithings.entities.Department">
            <column name="DEPARTMENT_ID" />
        </many-to-one>
        
    </class>
</hibernate-mapping>

Departmaent.java

public class Department {
    private Integer id;
	private String departmentName;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getDepartmentName() {
		return departmentName;
	}

	public void setDepartmentName(String departmentName) {
		this.departmentName = departmentName;
	}

	@Override
	public String toString() {
		return "Department [id=" + id + ", departmentName=" + departmentName
				+ "]";
	}
}

Department.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2014-7-22 11:21:48 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.ithings.entities.Department" table="SSH_DEPARTMENT">
      
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
      
        <property name="departmentName" type="java.lang.String">
            <column name="DEPARTMENT_NAME" />
        </property>
        
    </class>
</hibernate-mapping>

dao

public class BaseDao {
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public Session getSession(){
        return this.sessionFactory.getCurrentSession();
    }
}
public class EmployeeDao extends BaseDao {

    public void delete(Integer id) {
        String hql = "DELETE FROM Employee e WHERE e.id = ?";
        getSession().createQuery(hql).setInteger(0, id).executeUpdate();
    }

    public List<Employee> getAll() {
        String hql = "FROM Employee e LEFT OUTER JOIN FETCH e.department";
        return getSession().createQuery(hql).list();
    }

    public void saveOrUpdate(Employee employee) {
        getSession().saveOrUpdate(employee);
    }

    public Employee getEmployeeByLastName(String lastName) {
        String hql = "FROM Employee e WHERE e.lastName = ?";
        Query query = getSession().createQuery(hql).setString(0, lastName);
        Employee employee = (Employee) query.uniqueResult();
        System.out.println(employee.getDepartment().getClass().getName());
        return employee;
    }

    public Employee get(Integer id) {
        return (Employee) getSession().get(Employee.class, id);
    }
}

service

public class EmployeeService {

    private EmployeeDao employeeDao;

    public void setEmployeeDao(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }

    public List<Employee> getEmployeeList() {
        return employeeDao.getAll();
    }

    public Employee get(Integer id) {
        return employeeDao.get(id);
    }

    public boolean lastNameIsValid(String lastName) {
        return employeeDao.getEmployeeByLastName(lastName) == null;
    }

    public void saveOrUpdate(Employee employee) {
        employeeDao.saveOrUpdate(employee);
    }

    public void delete(Integer id) {
        employeeDao.delete(id);
    }
}

Action

public class EmployeeAction extends ActionSupport implements RequestAware, ModelDriven<Employee>,Preparable {
    private EmployeeService employeeService;
    private Integer id;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }
    
    public String list(){
        requestMap.put("employees", employeeService.getEmployeeList());
        return "list";
    }
    
    public String save(){
        employeeService.saveOrUpdate(employee);
        return "success";
    }
    public void prepareSave(){
        employee = new Employee();
    }
    public String edit(){
        return "edit";
    }
    public void prepareEdit(){
        employee = employeeService.get(id);
    }
    
    public String update(){
        employeeService.saveOrUpdate(employee);
        return "success";
    }
    public void prepareUpdate(){
        employee = employeeService.get(id);
    }
    public String delete(){
        employeeService.delete(id);
        return "success";
    }
    
    private Employee employee;
    @Override
    public Employee getModel() {
        return employee;
    }

    @Override
    public void prepare() throws Exception {
    }
    
    Map<String, Object> requestMap = new HashMap<String, Object>(); 
    @Override
    public void setRequest(Map<String, Object> map) {
        requestMap = map;
    }
}


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>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <package name="default" namespace="/" extends="struts-default">
        <!-- 定义新的拦截器栈, 配置 prepare 拦截器栈的 alwaysInvokePrepare 参数值为 false -->
        <interceptors>
            <interceptor-stack name="sshStack">
                <interceptor-ref name="paramsPrepareParamsStack">
                    <param name="prepare.alwaysInvokePrepare">false</param>
                </interceptor-ref>
            </interceptor-stack>
        </interceptors>
		
        <!-- 使用新的拦截器栈 -->
        <default-interceptor-ref name="sshStack"></default-interceptor-ref>
                
        <action name="emp-*" class="employeeAction"
        	method="{1}">
            <result name="list">/WEB-INF/pages/emp-list.jsp</result>
            <result name="success" type="redirect">/emp-list</result>
        </action>
				
    </package>
</struts>

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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- 导入资源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 配置 C3P0 数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		
        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>
	
    <!-- 配置 SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <property name="mappingLocations" value="classpath:com/ithings/entities/*.hbm.xml"></property>
    </bean>
     <!-- 配置 Spring 的声明式事务 -->
    <!-- 1. 配置 hibernate 的事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- 2. 配置事务属性 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="lastNameIsValid" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
	
    <!-- 3. 配置事务切入点, 再把事务属性和事务切入点关联起来 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.ithings.service.*.*(..))" id="txPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
   
</beans>

applicationContext-beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
">
    <bean id="employeeDao" class="com.ithings.dao.EmployeeDao">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <bean id="employeeService" class="com.ithings.service.EmployeeService">
        <property name="employeeDao" ref="employeeDao"></property>
    </bean>
    <bean id="employeeAction" class="com.ithings.actions.EmployeeAction"
            scope="prototype">
        <property name="employeeService" ref="employeeService"></property>	
    </bean>	
</beans>





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值