1. 程式人生 > >Maven搭建Spring+Struts2+Hibernate專案詳解

Maven搭建Spring+Struts2+Hibernate專案詳解

前言

       這篇主要採用Maven搭建Spring+Struts2+Hibernate的整合專案,複習一下SSH框架,雖然spring提供自己的MVC框架,但是Spring也提供和其他框架的無縫整合,採用元件形式對個框架進行管理,專案例項是按照真實企業裡面的開發搭建,也是web的最後一片了。資料庫使用mysql,連線池使用的是Druid資料來源(這些都無關緊要,可以隨時的替換),下面就將詳細的介紹一下Maven搭建Spring,Struts2,和hibernation的步奏。

1、資料庫設計

     資料庫庫表很簡單,設計好資料庫後,直接逆向生成實體,提高速度。資料庫名為shop,只有一個表user_info。其結構如下:

 

2、建立Maven的webapp專案

    建立maven專案,pom.xml配置中引入所需依賴包。

     

     引入所需的依賴包,pom.xml內容如下:

<span style="font-size:14px;">     <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.andy.ssh</groupId>
	<artifactId>spring_struts2_Hibernate_demo</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>

	<name>spring_struts2_Hibernate_demo Maven Webapp</name>
	<url>http://maven.apache.org</url>


	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>4.1.4.RELEASE</spring.version>
		<hibernate.version>4.3.8.Final</hibernate.version>
		<struts2.version>2.3.20</struts2.version>
		<jackson.version>2.5.0</jackson.version>
	</properties>

	<dependencies>

		<!-- junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<!-- spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- 關係型資料庫整合時需配置 如hibernate jpa等 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-ehcache</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<!-- struts2 -->
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>${struts2.version}</version>

			<exclusions>
				<exclusion>
					<!-- Hibernate已經還有該包的依賴 -->
					<artifactId>javassist</artifactId>
					<groupId>javassist</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-spring-plugin</artifactId>
			<version>${struts2.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-convention-plugin</artifactId>
			<version>${struts2.version}</version>
		</dependency>

		<!-- log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>

		<!-- mysql連線 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.34</version>
		</dependency>

		<!-- 資料來源 druid -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.12</version>
		</dependency>

		<!-- json -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.3</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>${jackson.version}</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>${jackson.version}</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.version}</version>
		</dependency>

		<!-- aop -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.4</version>
		</dependency>

		<!-- servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>spring_struts2_Hibernate_demo</finalName>

		<plugins>
			<!-- Run the JUnit unit tests in an isolated classloader -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.4.2</version>
				<configuration>
					<skipTests>true</skipTests>
				</configuration>

			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
				</configuration>
			</plugin>

			<!-- generate java doc -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.9.1</version>
				<configuration>
					<javadocDirectory>target/javadoc</javadocDirectory>
					<reportOutputDirectory>target/javadoc</reportOutputDirectory>
					<charset>UTF-8</charset>
					<encoding>UTF-8</encoding>
					<docencoding>UTF-8</docencoding>
					<show>private</show>
				</configuration>
			</plugin>

			<!-- 部署至本機 -->
			<plugin>
				<groupId>org.codehaus.cargo</groupId>
				<artifactId>cargo-maven2-plugin</artifactId>
				<version>1.0</version>
				<configuration>
					<container>
						<containerId>tomcat6x</containerId>
						<home>F:\apache-tomcat-7.0.27</home>
					</container>
					<configuration>
						<type>existing</type>
						<home>F:\apache-tomcat-7.0.27</home>
					</configuration>
				</configuration>
			</plugin>
		</plugins>

	</build>
</project>
</span>

以上就是ssh所需的所有依賴包。、

3、引入Spring

    最優先引入的是Spring框架,他是管理其他框架的容器,spring中需要配置的是自動掃描的dao,和service層的註解,然後將其注入為bean,管理。

     配置檔案在src/main/java目錄下,建立spring的配置檔案spring.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
			http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
			http://www.springframework.org/schema/context
			http://www.springframework.org/schema/context/spring-context-4.1.xsd">
	<!-- 載入配置檔案 -->
	
	<context:property-placeholder location="classpath:config.properties"/>
	<!-- 掃描service自動注入為bean -->
	<context:component-scan base-package="org.andy.shop.service.impl,org.andy.shop.dao.impl" />

</beans>

3.1、引入日誌Log4j配置

    log4j.properties配置內容如下:

### set log levels ###
log4j.rootLogger = INFO , C , D , E 

### console ###
log4j.appender.C = org.apache.log4j.ConsoleAppender
log4j.appender.C.Target = System.out
log4j.appender.C.layout = org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern = [spring_struts2_Hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

### log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ../logs/spring_struts2_Hibernate_demo.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = [spring_struts2_Hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

### exception ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = ../logs/spring_struts2_Hibernate_demo_error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = [spring_struts2_Hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

3.2、專案配置檔案

   新增專案的配置檔案config.properties,有spring管理。

#application configs

#jdbc druid config
validationQuery = SELECT 1
jdbc.url = jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = root

#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = false
hibernate.hbm2ddl.auto = update


4、引入Hibernation

    Hibernation的配置主要有如下內容:資料來源,SessionFactory,事務等的配置。

    spring-hibernate.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:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">

	<!-- 配置資料來源 使用的是Druid資料來源 -->
	<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		<!-- 初始化連線大小 -->
		<property name="initialSize" value="0" />
		<!-- 連線池最大使用連線數量 -->
		<property name="maxActive" value="20" />
		
		<!-- 連線池最小空閒 -->
		<property name="minIdle" value="0" />
		<!-- 獲取連線最大等待時間 -->
		<property name="maxWait" value="60000" />
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize"
			value="33" />
		<!-- 用來檢測有效sql -->
		<property name="validationQuery" value="${validationQuery}" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />
		<property name="testWhileIdle" value="true" />
		<!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<!-- 配置一個連線在池中最小生存的時間,單位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="25200000" />
		<!-- 開啟removeAbandoned功能 -->
		<property name="removeAbandoned" value="true" />
		<!-- 1800秒,也就是30分鐘 -->
		<property name="removeAbandonedTimeout" value="1800" />
		<!-- 關閉abanded連線時輸出錯誤日誌 -->
		<property name="logAbandoned" value="true" />
		<!-- 監控資料庫 -->
		<property name="filters" value="mergeStat" />
	</bean>

	<!-- 配置hibernate的SessionFactory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 注入資料來源 相關資訊看原始碼 -->
		<property name="dataSource" ref="dataSource" />
		<!-- hibernate配置資訊 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
			</props>
		</property>
		<!-- 掃描hibernate註解配置的entity -->
		<property name="packagesToScan" value="org.andy.shop.entity" />
	</bean>

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

	<!-- 配置事務增強處理Bean,指定事務管理器 -->
	<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
		<!-- 配置詳細事務處理語義 -->
		<tx:attributes>
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />

			<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="load*" propagation="SUPPORTS" read-only="true" />

			<!-- 其他採用預設事務方式 -->
			<tx:method name="*" />

		</tx:attributes>
	</tx:advice>

	<!-- Spring aop事務管理 -->
	<aop:config>
		<!-- 配置切入點 -->
		<aop:pointcut id="transactionPointcut"
			expression="execution(* org.andy.shop.service.impl.*Impl.*(..))" />
		<!-- 指定在txAdvice切入點應用txAdvice事務增強處理 -->
		<aop:advisor pointcut-ref="transactionPointcut"
			advice-ref="transactionAdvice" />
	</aop:config>

</beans>

注意:Hibernation4使用的是SessionFactory而不是HibernationTemplate。

5、生成實體

      我們先新增實體entity,Dao,Service,Action等幾個包,一般設計如下:

            

設計好資料表之後,採用Hibernation tools自動逆向生成實體,其實體UserInfo如下:

package org.andy.shop.entity;

// Generated 2015-2-13 12:48:39 by Hibernate Tools 4.0.0

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * UserInfo generated by hbm2java
 */
@Entity
@Table(name = "user_info", catalog = "shop")
public class UserInfo implements java.io.Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5127853981202454040L;
	private int id;
	private String name;
	private Integer age;
	private String telephone;

	public UserInfo() {
	}

	public UserInfo(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public UserInfo(int id, String name, Integer age, String telephone) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.telephone = telephone;
	}

	@Id
	@Column(name = "id", unique = true, nullable = false)
	public int getId() {
		return this.id;
	}

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

	@Column(name = "name", nullable = false)
	public String getName() {
		return this.name;
	}

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

	@Column(name = "age")
	public Integer getAge() {
		return this.age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Column(name = "telephone")
	public String getTelephone() {
		return this.telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

}

6、建立Dao層

    我們採用面向介面程式設計,所以先設計介面,在寫dao的實現類,其理,同樣適用於service層。

6.1、Dao層介面

   我們先定義一個通用的GenericDao介面,如下:

package org.andy.shop.dao;

import java.io.Serializable;
import java.util.List;

/**
 * 建立時間:2015-2-11 下午2:26:42
 * 
 * @author andy
 * @version 2.2
 * 
 * Dao通用介面
 */

interface GenericDao<T, PK extends Serializable> {
	
	T load(PK id);
	
	T get(PK id);
	
	List<T> findAll();
	
	void persist(T entity);
	
	PK save(T entity);
	
	void saveOrUpdate(T entity);
	
	void delete(PK id);
	
	void flush();
}

   具體的UserInfo的Dao介面UserInfoDao如下:

package org.andy.shop.dao;

import org.andy.shop.entity.UserInfo;

/**  
 * 建立時間:2015-2-13 下午12:49:55  
 * @author andy  
 * @version 2.2  
 * 描述: userDao 
 */

public interface UserInfoDao extends GenericDao<UserInfo, Integer> {

}

6.2、Dao層實現類

   UserInfo的Dao層實現類UserInfoDaoImpl如下:

package org.andy.shop.dao.impl;

import java.util.List;

import org.andy.shop.dao.UserInfoDao;
import org.andy.shop.entity.UserInfo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * 建立時間:2015-2-13 下午12:51:47
 * 
 * @author andy
 * @version 2.2 
 * 描述: dao實現類
 */

@Repository("userInfoDao")
public class UserInfoDaoImpl implements UserInfoDao {

	@Autowired
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return this.sessionFactory.getCurrentSession();
	}

	@Override
	public UserInfo load(Integer id) {
		return (UserInfo) this.getCurrentSession().load(UserInfo.class, id);
	}

	@Override
	public UserInfo get(Integer id) {
		return (UserInfo) this.getCurrentSession().get(UserInfo.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserInfo> findAll() {
		List<UserInfo> userInfos = this.getCurrentSession()
				.createQuery("from UserInfo").list();
		return userInfos;
	}

	@Override
	public void persist(UserInfo entity) {
		this.getCurrentSession().persist(entity);

	}

	@Override
	public Integer save(UserInfo entity) {
		return (Integer) this.getCurrentSession().save(entity);
	}

	@Override
	public void saveOrUpdate(UserInfo entity) {
		this.getCurrentSession().saveOrUpdate(entity);
	}

	@Override
	public void delete(Integer id) {
		UserInfo entity = this.load(id);
		this.getCurrentSession().delete(entity);
	}

	@Override
	public void flush() {
		this.getCurrentSession().flush();

	}

}

我們採用@Repository註解將其注入為dao的bean,交由spring管理。

7、建立Service層

   Service層同理按照面向介面程式設計。

7.1、Service層介面

   UserInfo層介面UserInfoService如下:

package org.andy.shop.service;

import java.util.List;

import org.andy.shop.entity.UserInfo;

/**  
 * 建立時間:2015-2-13 下午1:00:51  
 * @author andy  
 * @version 2.2  
 * 描述: 
 */

public interface UserInfoService {
	UserInfo load(Integer id);

	UserInfo get(Integer id);

	List<UserInfo> findAll();

	void persist(UserInfo entity);

	Integer save(UserInfo entity);

	void saveOrUpdate(UserInfo entity);

	void delete(Integer id);

	void flush();
}

7.2、service層實現類

   service層我們使用@Service註解將其注入為bean。

package org.andy.shop.service.impl;

import java.util.List;

import org.andy.shop.dao.UserInfoDao;
import org.andy.shop.entity.UserInfo;
import org.andy.shop.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 建立時間:2015-2-13 下午1:03:47
 * 
 * @author andy
 * @version 2.2 描述:
 */
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {

	@Autowired
	private UserInfoDao userInfoDao;

	@Override
	public UserInfo load(Integer id) {
		return null;
	}

	@Override
	public UserInfo get(Integer id) {
		return userInfoDao.get(id);
	}

	@Override
	public List<UserInfo> findAll() {
		return userInfoDao.findAll();
	}

	@Override
	public void persist(UserInfo entity) {
		userInfoDao.persist(entity);
	}

	@Override
	public Integer save(UserInfo entity) {
		return userInfoDao.save(entity);
	}

	@Override
	public void saveOrUpdate(UserInfo entity) {
		userInfoDao.saveOrUpdate(entity);
	}

	@Override
	public void delete(Integer id) {
		userInfoDao.delete(id);
	}

	@Override
	public void flush() {
		userInfoDao.flush();
	}

}

8、單元測試Spring和Hibernation框架的整合

   以上,spring和Hibernation框架就算是整合完成了,我們需要測試一下是否整合成功,事務是否起作用等,所以我們需要在src/test/java源目錄中編寫測試類,進行測試:

   我們建立了TestUserService類,進行單元測試:

  

 TestUserService內容如下:

package org.andy.shop.service;

import org.andy.shop.entity.UserInfo;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alibaba.fastjson.JSON;

/**
 * 建立時間:2015-2-13 下午3:31:07
 * 
 * @author andy
 * @version 2.2
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring.xml",
		"classpath:spring-hibernate.xml" })
public class TestUserService {

	private static final Logger LOGGER = Logger
			.getLogger(TestUserService.class);

	@Autowired
	private UserInfoService userInfoService;

	@Test
	public void save() {
		UserInfo userInfo = new UserInfo();
		userInfo.setName("zty");
		userInfo.setAge(23);
		userInfo.setTelephone("13212221333");
		Integer id = userInfoService.save(userInfo);
		JSON.toJSONString(id);
	}

}

我們需要引入springjunit的包,將spring配置載入,如果單元測試成功,那麼專案搭建已經成功了一半了。

9、引入Struts2

  配置Struts框架的配置檔案,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>
	<!-- 指定由spring負責action物件的建立 -->
	<constant name="struts.objectFactory" value="spring" />
	<!-- 所有匹配*.action的請求都由struts2處理 -->
	<constant name="struts.action.extension" value="action" />
	<!-- 是否啟用開發模式 -->
	<constant name="struts.devMode" value="true" />
	<!-- struts配置檔案改動後,是aa否重新載入 -->
	<constant name="struts.configuration.xml.reload" value="true" />
	<!-- 設定瀏覽器是否快取靜態內容 -->
	<constant name="struts.serve.static.browserCache" value="false" />
	<!-- 請求引數的編碼方式 -->
	<constant name="struts.i18n.encoding" value="utf-8" />
	<!-- 每次HTTP請求系統都重新載入資原始檔,有助於開發 -->
	<constant name="struts.i18n.reload" value="true" />
	<!-- 檔案上傳最大值 -->
	<constant name="struts.multipart.maxSize" value="104857600" />
	<!-- 讓struts2支援動態方法呼叫 -->
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
	<!-- Action名稱中是否還是用斜線 -->
	<constant name="struts.enable.SlashesInActionNames" value="false" />
	<!-- 允許標籤中使用表示式語法 -->
	<constant name="struts.tag.altSyntax" value="true" />
	<!-- 對於WebLogic,Orion,OC4J此屬性應該設定成true -->
	<constant name="struts.dispatcher.parametersWorkaround" value="false" />

	<!-- 用於CRUD Action的parent package -->
	<package name="crud-default" extends="convention-default">
		<!-- 基於paramsPrepareParamsStack, 增加store interceptor保證actionMessage在redirect後不會丟失 -->
		<interceptors>
			<interceptor-stack name="crudStack">
				<interceptor-ref name="store">
					<param name="operationMode">AUTOMATIC</param>
				</interceptor-ref>
				<interceptor-ref name="paramsPrepareParamsStack" />
			</interceptor-stack>
		</interceptors>
		<default-interceptor-ref name="crudStack" />
	</package>

	<!-- 使用Convention外掛,實現約定大於配置的零配置檔案風格. 特殊的Result路徑在Action類中使用@Result設定. -->

</struts>

上面配置的比較詳細,可以按照實際專案,做一下篩檢。

10、配置web容器web.xml

    web.xml是web專案的核心,裡面配置了容器啟動是的載入檔案,以及監聽器,過濾器等內容,所以需要我們配置對個框架的啟動,載入。其內容如下:

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	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>spring_struts2_Hibernate_demo</display-name>

	<!-- spring 和  Hibernate的配置檔案 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
		     classpath:spring.xml
		     classpath:spring-hibernate.xml
	    </param-value>
	</context-param>

	<!-- 編碼設定 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- openSessionInView配置 作用是延遲session關閉到view層 -->
	<filter>
		<filter-name>openSessionInViewFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
		<init-param>
			<param-name>singleSession</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<!-- 監聽servletContext,啟動contextConfigLocation中的spring配置資訊 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 防止spring記憶體溢位監聽器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<!-- 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>*.action</url-pattern>
	</filter-mapping>


	<filter-mapping>
		<filter-name>openSessionInViewFilter</filter-name>
		<url-pattern>*.action</url-pattern>
	</filter-mapping>

	<!-- 配置session超時時間,單位分鐘 -->
	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>

	<welcome-file-list>
		<welcome-file>/index.jsp</welcome-file>
	</welcome-file-list>
</web-app>
注意:上面Hibernation4和3還是有點區別的。

11、建立控制層Action

    控制層Struts2我們採用annotation 約束註解方式實現action的零配置,需要我們在WEB-INF下建立content目錄(必須是content),裡面存放是檢視層jsp。

    UserinfoAction內容如下:

package org.andy.shop.action;

import java.util.List;

import org.andy.shop.entity.UserInfo;
import org.andy.shop.service.UserInfoService;
import org.andy.shop.utils.AjaxUtil;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

/**
 * 建立時間:2015-2-13 下午2:49:22
 * 
 * @author andy
 * @version 2.2 描述: user的Action
 */
@Namespace("/user")
public class UserinfoAction extends ActionSupport implements
		ModelDriven<UserInfo>, Preparable {
	private static final long serialVersionUID = -2301203156032690317L;

	private static final Logger LOGGER = Logger.getLogger(UserinfoAction.class);
	private Integer id;
	private UserInfo userInfo;
	private List<UserInfo> userInfos;

	@Autowired
	private UserInfoService userInfoService;

	public Integer getId() {
		return id;
	}

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

	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public List<UserInfo> getUserInfos() {
		return userInfos;
	}

	public void setUserInfos(List<UserInfo> userInfos) {
		this.userInfos = userInfos;
	}

	@Override
	public UserInfo getModel() {
		if (null != id) {
			userInfo = userInfoService.get(id);
		} else {
			userInfo = new UserInfo();
		}
		return userInfo;
	}

	@Override
	public String execute() throws Exception {
		LOGGER.info("查詢所有使用者");
		userInfos = userInfoService.findAll();
		return SUCCESS;
		
	}

	public void detail() {
		String id = ServletActionContext.getRequest().getParameter("id");
		LOGGER.info("檢視使用者詳情:" + id);
		userInfo = userInfoService.get(Integer.valueOf(id));
		AjaxUtil.ajaxJSONResponse(userInfo);

	}

	@Override
	public void prepare() throws Exception {
		
	}

}

按照約束原則,上面success是會跳轉到content下的/user/userinfo.jsp檢視。

注意:如果上述的UserinfoAction寫出了UserInfoAction,那麼對應的檢視為/user/user-info.jsp,對應的Action為user-info.action

12、建立檢視層

   檢視userinfo.jsp內容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<title>userInfo</title>
</head>
<body>
	全部使用者資訊:
	<c:forEach items="${ userInfos}" var="user">
	    <div>  姓名:${user.name }   年齡:${user.age }    電話: ${user.telephone }  <a target="_blank" href="user/userinfo!detail.action?id=${user.id}">json詳情</a></div>
	</c:forEach>

</body>
</html>

通過這個檢視,我們可以測試UserinfoAction中的兩個url。

13、部署伺服器測試

   使用Maven打包部署:clean compile  package

    測試   http://localhost:8080/spring_struts2_Hibernate_demo/user/userinfo.action

            

   json返回資料  http://localhost:8080/spring_struts2_Hibernate_demo/user/userinfo!detail.action?id=1

         

OK,到此為止Spring+Struts2+Hibernate全部搭建完成。