框架(Spring、Struts2和Hibernate三者)整合

D燦發表於2017-03-13

總結一下就是:

1.Struts2與Spring相連的是:action不是Struts2框架new 出來的,而是從Spring的xml(applicationContext.xml)配置檔案中拿出

2.Spring和Hibernate相通的是:Hibernate的SessionFactory採用Spring注入,同時dao的實現類繼承Spring的類(HibernateDaoSupport)

3.其他的進入哪個領域就使用哪個框架

 

具體解釋見程式碼:

springStruts2Hibernate

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>	
  <!-- 載入Spring配置檔案 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 配置字元過濾器,解決亂碼問題 -->
  <filter>
  	<filter-name>encodingFilter</filter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>encodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- 解決因session關閉而導致的延遲載入例外的問題 -->
	<filter>
		<filter-name>lazyLoadingFilter</filter-name>
		<filter-class>
			org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
		</filter-class>
	</filter>
  
  <!-- 配置Struts -->
  <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.jsp</welcome-file>
  </welcome-file-list>
</web-app>


伺服器啟動查詢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:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

	<bean id="regAction" class="cn.hncu.action.RegAction">
		<property name="dao" ref="dao"></property>
	</bean>
	<bean id="dao" class="cn.hncu.dao.CustomerDaoJdbc" >
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 配置sessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation" value="/WEB-INF/hibernate.cfg.xml">
		</property>
	</bean>
	
	<!-- 配置事務管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 定義事務傳播特性 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="*" read-only="true"/><!--  除了上面定義的,其他的方法不走事務 -->
		</tx:attributes>
	</tx:advice>
	<!-- 哪些類需要事務 -->
	<aop:config>
		<aop:pointcut id="alladdmethod"
			expression="execution(* cn.hncu.dao.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="alladdmethod" />
	</aop:config>
 </beans>


由Spring來new出來bean配置的類

第一個bean:RegAction.java

package cn.hncu.action;

import cn.hncu.dao.CustomerDao;
import cn.hncu.domain.Customer;

import com.opensymphony.xwork2.ActionSupport;

public class RegAction extends ActionSupport{
	private String customerId;
	private String name;
	private String phone;
	
	private CustomerDao dao;

	public RegAction() {
	}

	public String getCustomerId() {
		return customerId;
	}

	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public CustomerDao getDao() {
		return dao;
	}

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

	@Override
	public String execute() throws Exception {
		try {
			Customer cus=new Customer();
			cus.setCustomerId(this.getCustomerId());
			cus.setName(this.getName());
			cus.setPhone(this.phone);
			this.getDao().addCustomer(cus);
			return "success";
		} catch (Exception e) {
			return "input";
		}
	}
	
}


第二個bean:CustomerDao.java介面

package cn.hncu.dao;

import cn.hncu.domain.Customer;

public interface CustomerDao {
	public abstract void addCustomer(Customer customer);
}


實現類CustomerDaoJdbc.java

package cn.hncu.dao;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.hncu.domain.Customer;

public class CustomerDaoJdbc extends HibernateDaoSupport implements CustomerDao {

	@Override
	public void addCustomer(Customer customer) {
		try {
			System.out.println(customer);
//			Session session=this.getSession();
//			Transaction tr=session.beginTransaction();
//			session.saveOrUpdate(customer);
//			tr.commit();
//			session.close();
			this.getHibernateTemplate().save(customer);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
	}

}


Hibernate的配置檔案hibernate.cfg.xml

<?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>
	<property name="connection.username">hncu</property>
	<property name="connection.url">
		jdbc:mysql://127.0.0.1:3306/mydb
	</property>
	<property name="dialect">
		org.hibernate.dialect.MySQLDialect
	</property>
	<property name="myeclipse.connection.profile">mysql1</property>
	<property name="connection.password">1234</property>
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<mapping resource="cn/hncu/domain/Customer.hib.xml" />

</session-factory>

</hibernate-configuration>


值物件Customer.java

package cn.hncu.domain;

public class Customer {
	private String customerId;
    private String name;
    private String phone;
   public Customer() {
   }
   public Customer(String customerId) {
       this.customerId = customerId;
   }
   public Customer(String customerId, String name, String phone) {
       this.customerId = customerId;
       this.name = name;
       this.phone = phone;
   }
   public String getCustomerId() {
       return this.customerId;
   }
   public void setCustomerId(String customerId) {
       this.customerId = customerId;
   }
   public String getName() {
      return this.name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public String getPhone() {
       return this.phone;
   }
   public void setPhone(String phone) {
       this.phone = phone;
   }
@Override
public String toString() {
	return "Customer [customerId=" + customerId + ", name=" + name + ", phone="
			+ phone + "]";
}
   
}


值物件的對映檔案Customer.hib.xml

<?xml version="1.0" encoding="utf-8"?>  
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping>
	
	<class name="cn.hncu.domain.Customer" table="customers" catalog="mydb">
		<id name="customerId" type="java.lang.String">
			<column name="customerID" length="8"></column>
			<generator class="assigned"></generator>
		</id>
		 <property name="name" type="java.lang.String">
            <column name="name" length="40" />
        </property>
        <property name="phone" type="java.lang.String">
            <column name="phone" length="16" />
        </property>
	</class>
</hibernate-mapping>


index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>註冊頁面</title>
  </head>
  
  <body>
   		<s:form action="regAction.action" method="post">
   			<s:textfield name="customerId" label="客戶編號"></s:textfield>
   			<s:textfield name="name" label="客戶姓名"/>
   			<s:textfield name="phone" label="客戶電話"></s:textfield>
   			<s:submit value="提交" align="center"></s:submit>
   		</s:form>
  </body>
</html>


index的form表單請求regAction時請求,查詢struts.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="add" extends="struts-default">
		<action name="regAction" class="cn.hncu.action.RegAction">
			<result name="success">/jsps/success.jsp</result>
			<result name="input">/index.jsp</result>
		</action>
	</package>
</struts>


成果展示:

主頁

 

提交成功:


同時儲存到資料庫中:

 

經測試,成功整合。

注:

注意:專案部署到web伺服器中可能報錯,因為Spring 2.5 AOP Libraries中的asm的三個jar包會和Hibernate 3.2 Core Libraries中的asmjar包中的某些類中有衝突。所以一定要刪除Spring中的三個asmjar包。


相關文章