1. 程式人生 > >【SSH】:基於Struts2+HIbernate3+Spring3實現員工管理系統之框架整合篇

【SSH】:基於Struts2+HIbernate3+Spring3實現員工管理系統之框架整合篇

       SSH知識點回顧

       這個不用多說,老師畫的一張圖還是可以的:

 

       搭建SSH開發環境

       版本比較舊,但是方法還是好的,給初學者還是很大幫助的。

       SSH整合的三種方式:

       1、帶有HIbernate配置檔案的方式

       2、不帶有HIbernate配置檔案的方式

       3、純註解的

       這一次我們採用第二種方式來進行SSH框架整合。

       步驟一:建立web專案並引入相應的jar包

       Struts2框架開發的相應的jar包

       一般我們都去這個路徑下struts-2.3.31\apps\struts2-blank\WEB-INF\lib索取開發的jar包:

       

       然後再去struts-2.3.31\lib索取其它比較重要的jar包:

       struts2-convention-plugin-2.3.31.jar:Struts2的註解開發的jar包

       struts2-spring-plugin-2.3.31.jar:Struts2用於整合Spring的jar包

       HIbernate框架開發的相應的jar包

       我們使用的Hibernate版本是hibernate-release-3.3.1.Final。

       hibernate-release-3.3.1.Final\lib\required\*.jar

       hibernate-release-3.3.1.Final\lib\jpa\*.jar

       Spring框架開發的相應的jar包

       spring-framework-3.2.0.RELEASE

       做Spring基本開發需要引入的jar包:

       IoC

       spring-beans-3.2.0.RELEASE.jar

       spring-context-3.2.0.RELEASE.jar

       spring-core-3.2.0.RELEASE.jar

       spring-expression-3.2.0.RELEASE.jar

       依賴的jar包

       com.springsource.org.apache.log4j-1.2.15.jar

       com.springsource.org.apache.commons.logging-1.1.1.jar

       AOP

       spring-aop-3.2.0.RELEASE.jar

       spring-aspects-3.2.0.RELEASE.jar

       依賴的jar包

       com.springsource.org.aopalliance-1.0.0.jar

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

       事務管理的jar包 

       spring-tx-3.2.0.RELEASE.jar

       整合HIbernate的包

       spring-orm-3.2.0.RELEASE.jar

       spring-jdbc-3.2.0.RELEASE.jar

       整合Web專案

       spring-web-3.2.0.RELEASE.jar

       整合Junit單元測試

       spring-test-3.2.0.RELEASE.jar

       連線池:

       com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar

       有關日誌記錄的jar包

       slf4j-log4j12-1.7.5.jar: slf4j整合log4j的jar包

       commons-logging-1.1.3.jar

       mysql-connector-java-5.1.22-bin.jar:MySQL資料庫驅動包

       步驟二:引入相關配置檔案

       這裡將已經配置好的配置檔案貼出來,後面很多的配置連線池和事務管理以及注入方式步驟省略。

       WebContent/WEB-INF/web.xml配置檔案的內容:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                  xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
                  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
                                                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
                  id="WebApp_ID" 
                  version="3.1">
  <display-name>struts2_spring3_hibernate3</display-name>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <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>
  
  <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>
       struts.xml配置檔案

       在src目錄下引入struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC 
       "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" 
       "http://struts.apache.org/dtds/struts-2.1.dtd">


<struts>
<package name="ssh" namespace="/" extends="struts-default">
<action name="product_*" class="productAction" method="{1}">
</action> 
</package>
</struts>    

       src/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">

<!-- 引入外部的屬性檔案 -->
<context:property-placeholder location="classpath:jdbc.properties"/>

<!-- 配置連線池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>

<!-- 配置Hibernate的相關屬性 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 注入連線池 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 載入Hibernate相關屬性 -->
<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>
<!-- 載入hibernate中的對映檔案 -->
<property name="mappingResources">
<list>
<value>com/demo/domain/Product.hbm.xml</value>
</list>
</property>
</bean>

<!-- 配置Action的類 -->
<bean id="productAction" class="com.demo.action.ProductAction" scope="prototype">
<property name="productService" ref="productService"></property>
</bean>

<!-- 配置業務層的類 -->
<bean id="productService" class="com.demo.service.ProductService">
<property name="productDao" ref="productDao"></property>
</bean>

<!-- 配置DAO的類 -->
<bean id="productDao" class="com.demo.dao.ProductDao">
<property name="sessionFactory" ref="sessionFactory"></property> 
</bean>

<!-- 配置事務管理 -->
<bean id="transaction" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<!-- 開啟註解事務 -->
<tx:annotation-driven transaction-manager="transaction"></tx:annotation-driven>

</beans>

       src/jdbc.properties屬性配置檔案的內容:

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssh
jdbc.username=root
jdbc.password=root

       src/log4j.properties屬性配置檔案的內容:

log4j.rootLogger = debug, console, E
#level=INFO,all can be output
#console is set to be a ConsoleAppender
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = [%p] %d{yyyy-MM-dd HH:mm:ss} - %m%n


#file is set to output to a extra file
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.Threshold=error
log4j.appender.E.Encoding=UTF-8
log4j.appender.E.layout.ConversionPattern=[%p] %d{yyyy-MM-dd HH:mm:ss} - %m%n
log4j.appender.E.DatePattern='.'yyyy-MM-dd
log4j.appender.E.File = ${catalina.base}/logs/dd/error.log

       步驟三:建立包結構

       

       步驟四:建立頁面(儲存商品)

       addProduct.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增商品頁面</title>
</head>
<body>
     <h1>儲存商品的頁面</h1>
	<s:form action="product_save" method="post" theme="simple" namespace="/">
		<table border="1" width="400">
			<tr>
				<td>商品名稱:</td>
				<td><s:textfield name="pname"></s:textfield></td>
			</tr>
			<tr>
				<td>商品價格:</td>
				<td><s:textfield name="price"></s:textfield></td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" value="新增" /></td>
			</tr>
		</table>
	</s:form>
</body>
</html>

       步驟五:編寫實體類、物件關係對映檔案、Action、Service和DAO

       Product.java

package com.demo.domain;

/**
 * 商品實體類
 * @author Administrator
 * @date 2016年12月24日
 */
public class Product {
	private Integer pid;
	private String pname;
	private Double price;
	
	public Integer getPid() {
		return pid;
	}
	
	public void setPid(Integer pid) {
		this.pid = pid;
	}
	
	public Double getPrice() {
		return price;
	}
	
	public String getPname() {
		return pname;
	}
	
	public void setPname(String pname) {
		this.pname = pname;
	}
	
	public void setPrice(Double price) {
		this.price = price;
	}
	
}

       Product.hbm.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="com.demo.domain.Product" table="product">
		<id name="pid" column="pid">
			<generator class="native"></generator>
		</id>
		<property name="pname" column="pname" length="20"></property>
		<property name="price" column="price"></property>
	</class>
</hibernate-mapping>

       ProductAction.java

package com.demo.action;

import com.demo.domain.Product;
import com.demo.service.ProductService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 商品管理的action類
 * @author Administrator
 * @date 2016年12月24日
 */
@SuppressWarnings("serial")
public class ProductAction extends ActionSupport implements ModelDriven<Product>{
	//模型驅動使用的類
	private Product product = new Product();
	
	@Override
	public Product getModel() {
		return product;
	}
	
	//Struts2和Spring整合過程中按名稱注入的業務層的類
	private ProductService productService;
	
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}
	
	/**
	 * action儲存商品的執行方法:save()
	 * @return
	 */
	public String save(){
		System.out.println("Action中的save()方法執行了");
		productService.save(product);
		return NONE;
	}
	
}

       ProductService.java

package com.demo.service;

import org.springframework.transaction.annotation.Transactional;

import com.demo.dao.ProductDao;
import com.demo.domain.Product;

/**
 * 商品管理的service類
 * @author Administrator
 * @date 2016年12月24日
 */
@Transactional
public class ProductService {
	//業務層注入DAO的類
	private ProductDao productDao;

	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}

	/**
	 * 業務層儲存商品的方法
	 * @param product
	 */
	public void save(Product product) {
		System.out.println("Service中的save()方法執行了");
		productDao.save(product);
	}
	
}

       ProductDao.java

package com.demo.dao;

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

import com.demo.domain.Product;

/**
 * 商品管理的dao類
 * @author Administrator
 * @date 2016年12月24日
 */
public class ProductDao extends HibernateDaoSupport {
	
	/**
	 * DAO中儲存商品的方法
	 * @param product
	 */

public void save(Product product) { System.out.println("DAO中的save()方法執行了"); this.getHibernateTemplate().save(product); } }

       步驟六:配置Action、Service和DAO

       Struts2和Spring整合的兩種方式:

       1、Action的類由Struts2自身去建立
       Action的配置:struts.xml

      <package name="ssh" namespace="/" extends="struts-default">
		<action name="product_*" class="com.demo.action.ProductAction" method="{1}"></action> 
      </package>
       Service和DAO是如何配置的
       直接在applicationContext.xml中進行配置
        <!-- 配置業務層的類 -->
	<bean id="productService" class="com.demo.service.ProductService">
		<property name="productDao" ref="productDao"></property>
	</bean>
	
	<!-- 配置DAO的類 -->
	<bean id="productDao" class="com.demo.dao.ProductDao" />
       2、Action的類交給Spring框架建立
       Action、Service和DAO的配置:applicationContext.xml
        <!-- 配置Action的類 -->
	<bean id="productAction" class="com.demo.action.ProductAction" scope="prototype">
		<property name="productService" ref="productService"></property>
	</bean>
	
	<!-- 配置業務層的類 -->
	<bean id="productService" class="com.demo.service.ProductService">
		<property name="productDao" ref="productDao"></property>
	</bean>
	
	<!-- 配置DAO的類 -->
	<bean id="productDao" class="com.demo.dao.ProductDao">
		<property name="sessionFactory" ref="sessionFactory"></property> 
	</bean>		
       Action配置
      <package name="ssh" namespace="/" extends="struts-default">
		<action name="product_*" class="productAction" method="{1}">
		</action> 
	</package>

       步驟七:建立資料庫

       create database ssh charset utf8;

       步驟八:Spring整合HIbernate

       在上面的Applicatiom.xml檔案已經配置。不管是注入方式還是事務管理,在上面的步驟基本都包括了,就不再

一一贅述。

       執行專案:

       

       控制檯輸出:

       

       資料庫的資料:

       

       上述的流程基本通過,下一篇就是實現案例:開發員工管理系統(一個小的示例)