码迷,mamicode.com
首页 > 编程语言 > 详细

struts2,spring,hibernate三大框架整合

时间:2015-04-01 13:27:47      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:s2sh   ssh   三大框架整合   s2sh整合   

    本文利用mvc三层架构来讲述S2SH三大框架整合的步骤:

1.建立好包结构,建立好的包结构如下:

技术分享

2.导入相应的jar包

(1)struts2用到的jar包

技术分享

(2)spring用到的jar包

技术分享

(3)hibernate用到的jar包

技术分享

(4)mysql驱动包,junit和struts2插件

技术分享

(5)公共包,例如日志

commons-logging-1.1.3.jar
log4j-1.2.17.jar
slf4j-log4j12-1.5.0.jar

最后经过整理的jar包清单如下:

antlr-2.7.6.jar
aopalliance.jar
asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
aspectjrt.jar
aspectjweaver.jar
commons-collections-3.1.jar
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
commons-lang3-3.1.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
freemarker-2.3.19.jar
hibernate3.jar
javassist-3.11.0.GA.jar
jta-1.1.jar
junit.jar
log4j-1.2.17.jar
mysql-connector-java-5.1.10-bin.jar
ognl-3.0.6.jar
slf4j-api-1.5.8.jar
slf4j-log4j12-1.5.0.jar
spring-aop-3.2.2.RELEASE.jar
spring-aspects-3.2.2.RELEASE.jar
spring-beans-3.2.2.RELEASE.jar
spring-context-3.2.2.RELEASE.jar
spring-core-3.2.2.RELEASE.jar
spring-expression-3.2.2.RELEASE.jar
spring-jdbc-3.2.2.RELEASE.jar
spring-orm-3.2.2.RELEASE.jar
spring-tx-3.2.2.RELEASE.jar
spring-web-3.2.2.RELEASE.jar
struts2-core-2.3.16.1.jar
struts2-spring-plugin-2.3.16.1.jar
xwork-core-2.3.16.1.jar

3.相应的jar包导入完成后,就可以配置配置文件了

首先在config目录下建立如下的结构

技术分享

hibernate目录专门用来存放hibernate的配置文件,spring目录用来存放spring配置文件,struts用来存放struts配置文件

(1)首先配置好hibernate的配置文件

文件路径:${项目路径}/config/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.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<property name="connection.url">jdbc:mysql:///s2sh</property>
		<property name="connection.username">root</property>
		<property name="connection.password">123456</property>
		<!-- 方言 -->
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		
		<!-- 每次都检查表结构,如果表不存在则创建 -->
		<property name="hbm2ddl.auto">update</property>
		<!-- 显示sql语句,开发时启用 -->
		<property name="show_sql">true</property>
	</session-factory>
</hibernate-configuration>
(2)配置spring

为了便于管理,将spring的配置文件作为不同的文件存放,最后在applicationContext.xml文件中引入

      首先是配置spring事务管理:

      文件路径:${项目路径}/config/spring/applicationContext-db.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.xsd
	     http://www.springframework.org/schema/tx
	     http://www.springframework.org/schema/tx/spring-tx.xsd
	     http://www.springframework.org/schema/aop
	     http://www.springframework.org/schema/aop/spring-aop.xsd">
	<!-- 配置sessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation">
			<value>classpath:hibernate/hibernate.cfg.xml</value>
		</property>
	</bean>
	
	<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref bean="sessionFactory"/>
		</property>
	</bean>
	
	<!-- 配置通知 -->
	<tx:advice id="tx" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="save*"/>
			<tx:method name="update*"/>
			<tx:method name="delete*"/>
			<tx:method name="*" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	<!-- aop配置 -->
	<aop:config>
		<!-- 切入点表达式 -->
		<aop:pointcut expression="execution(* cn.zq.service.impl.*.*(..))" id="perform"/>
		<aop:advisor advice-ref="tx" pointcut-ref="perform"/>
	</aop:config>
</beans>

4.创建Person类以及Dao,Service,Action

(1)创建Person

package cn.zq.bean;

public class Person {
	private Long id;
	private String name;
	private Integer age;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
}
(2)配置Person的hibernate的映射文件

文件路径:${项目路径}/src/cn/zq/bean/Person.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 package="cn.zq.bean">
	<class name="Person" table="person" >
		<id name="id" type="long" length="10" >
			<generator class="increment"></generator>
		</id>
		<property name="name" type="string" length="36" column="name" />
		<property name="age" type="integer"/>
	</class>
</hibernate-mapping>

并在hibernate.cfg.xml配置文件中引入

<mapping resource="cn/zq/bean/Person.hbm.xml" />
(3)创建Dao

package cn.zq.dao;

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

import cn.zq.bean.Person;

/**
 * 
 * @author zq
 *
 */
public interface PersonDao {
	
	/**
	 * save <b>Person</b> to DB.
	 * @param p The <code>Person</code> object to be saved.
	 */
	void savePerson(Person p);
	
	/**
	 * Find Person by id from DB.
	 * @param pid The primary key.
	 * @return Person instance or null if not found.
	 */
	Person findPersonById(Serializable pid);
	
	
	/**
	 * Find all Person from DB.
	 * @return Person collections.
	 */
	List<Person> findAll();
}


package cn.zq.dao.impl;

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

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

import cn.zq.bean.Person;
import cn.zq.dao.PersonDao;

/**
 * 
 * @author zq
 *
 */
public class PersonDaoImpl extends HibernateDaoSupport 
						implements PersonDao{

	public void savePerson(Person p) {
		getHibernateTemplate().save(p);
	}

	public Person findPersonById(Serializable pid) {
		return getHibernateTemplate().get(Person.class, pid);
	}

	@SuppressWarnings("unchecked")
	public List<Person> findAll() {
		return getHibernateTemplate().find("from Person");
	}

}

(4)创建service



package cn.zq.service;

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

import cn.zq.bean.Person;

public interface PersonService {
	
	void savePerson(Person p);
	
	Person findPersonById(Serializable pid);
	
	List<Person> findAll();
}

package cn.zq.service.impl;

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

import cn.zq.bean.Person;
import cn.zq.dao.PersonDao;
import cn.zq.service.PersonService;

public class PersonServiceImpl implements PersonService{
	
	private PersonDao personDao;
	
	public PersonDao getPersonDao() {
		return personDao;
	}

	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}

	public void savePerson(Person p) {
		getPersonDao().savePerson(p);
	}

	public Person findPersonById(Serializable pid) {
		return getPersonDao().findPersonById(pid);
	}

	public List<Person> findAll() {
		return getPersonDao().findAll();
	}

}

(5)创建action

package cn.zq.struts2.action;

import java.util.List;
import java.util.Random;

import cn.zq.bean.Person;
import cn.zq.service.PersonService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class PersonAction extends ActionSupport{

	private static final long serialVersionUID = -7979618198537224040L;
	
	private PersonService personService;

	public PersonService getPersonService() {
		return personService;
	}

	public void setPersonService(PersonService personService) {
		this.personService = personService;
	}
	
	public String save(){
		Person p = new Person();
		Random random = new Random(13);
		p.setName("RiccioZhang" + random.nextInt(100));
		p.setAge(random.nextInt(30));
		getPersonService().savePerson(p);
		return null;
	}
	
	public String findAll(){
		List<Person> persons = getPersonService().findAll();
		ActionContext.getContext().getValueStack().push(persons);
		return "index";
	}
}





(6)创建struts2配置

和上面一样这个配置文件只用来存放一些公共的配置,其他配置在此引入

  文件路径:${项目路径}/config/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.objectFactory" value="spring"></constant> -->
	<constant name="struts.action.extension" value="action"></constant>
	<constant name="struts.devMode" value="true"></constant>

</struts>
(7)创建Person的struts2配置

  文件路径:${项目路径}/config/struts/struts-Person.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>
	<package name="person" namespace="/" extends="struts-default">
		<action name="personAction_*" class="personAction" method="{1}">
			<result name="index">/index.jsp</result>
		</action>
	</package>
</struts>
并在struts.xml引入

<include file="struts/struts-Person.xml"></include>

5.用spring管理Person的Dao,Service,Action的创建

文件路径:${项目路径}/config/spring/applicationContext-Person.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.xsd
	     http://www.springframework.org/schema/tx
	     http://www.springframework.org/schema/tx/spring-tx.xsd
	     http://www.springframework.org/schema/aop
	     http://www.springframework.org/schema/aop/spring-aop.xsd">
	
	<bean id="personDao" class="cn.zq.dao.impl.PersonDaoImpl">
		<property name="sessionFactory">
			<ref bean="sessionFactory"/>
		</property>
	</bean>
	<bean id="personService" class="cn.zq.service.impl.PersonServiceImpl">
		<property name="personDao" ref="personDao"></property>
	</bean>
	<bean id="personAction" class="cn.zq.struts2.action.PersonAction" scope="prototype">
		<property name="personService" ref="personService"></property>
	</bean>
</beans>

并在applicationContext.xml文件中引入

<import resource="applicationContext-Person.xml"/>


在此为此三大框架的整合基本上完成了,但是不要忘记了在web.xml文件中配置

6.在web,xml文件中整入spring,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" 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_3_0.xsd" id="WebApp_ID" version="3.0">
  
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:spring/applicationContext.xml</param-value>
  </context-param>
  
	
  <filter>
  	<filter-name>OpenSessionInViewFilter</filter-name>
  	<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>OpenSessionInViewFilter</filter-name>
	<url-pattern>*.action</url-pattern>  
  </filter-mapping>
  
  <filter>
  	<filter-name>StrutsPrepareAndExecuteFilter</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>StrutsPrepareAndExecuteFilter</filter-name>
	<url-pattern>/*</url-pattern>  
  </filter-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


7.完成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>Person List</title>
  </head>
  
  <body>
   	<table border="1">
   		<tr>
   			<td>ID</td>
   			<td>NAME</td>
   			<td>AGE</td>
   		</tr>
   		<s:iterator>
   			<tr>
   				<td>
   					<s:property value="id"/>
   				</td>
   				<td><s:property value="name"/></td>
   				<td><s:property value="age"/></td>
   			</tr>
   		</s:iterator>
   	</table>
  </body>
</html>

8.创建数据库s2sh

mysql> create database s2sh character set utf8;
Query OK, 1 row affected (0.03 sec)

9.部署并启动tomcat

为了能有日志信息输出,需要配置log4j

路径:${项目}/config/log4j.properties

# Set root logger level to WARN and append to stdout
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%d %5p (%c:%L) - %m%n

# Print only messages of level ERROR or above in the package noModule.
log4j.logger.noModule=FATAL

log4j.logger.com.opensymphony.xwork2=DEBUG
log4j.logger.org.apache.struts2=DEBUG
如果在启动时没有报错说明配置成功了,一般启动不会瞬间完成,要是非常快就启动完成了,那么说明肯定是报错了。

(1)首先访问http://localhost:8080/s2sh/personAction_save.action, 多访问几次以便多插入几行数据

   (2)访问http://localhost:8080/s2sh/personAction_findAll.action

技术分享
到此三大框架的整合工作算是完成了,接下来就可以在此基础上继续开发


本文的源代码可以在这里下载http://download.csdn.net/detail/qq791967024/8553253

struts2,spring,hibernate三大框架整合

标签:s2sh   ssh   三大框架整合   s2sh整合   

原文地址:http://blog.csdn.net/ricciozhang/article/details/44787949

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!