使用环境:myeclipse10
1、建立web project,在WEB-INF/lib/下导入所需的jar包 http://download.csdn.net/detail/yuxiangdo/6040645
hibernate核心安装包下:hibernate3.jar、lib\required\*.jar lib\optional\ehcache-1.2.3.jar
hibernate注解安装包下的:lib\test\slf4j-log4j12.jar
spring安装包下:dist\spring.jar、dist\modules\spring-webmvc-struts.jar
lib\jakarta-commons\commons-logging.jar、commons-dbcp.jar、commons-pool.jar
lib\aspectj\aspectjweaver.jar、aspectjrt.jar
lib\j2ee\common-annotations.jar
lib\log4j\log4j-1.2.15.jar
struts包下:struts-1.3.8-lib.zip中的所有jar,spring中已有antlr-2.7.6.jar,不需要antlr-2.7.2
数据库驱动包
2、先整合spring和hibernate,如建包com.yxd.bean,放pojo类,对象映射文件:Person.java、Person.hbm.xml
建包com.yxd,service.impl,放PersonServiceBean.java
右键Refactor->Extract interface抽取接口,则有com.yxd.service包下的PersonService接口类
在spring配置文件中,配置hibernate中的sessionFactory会话工厂(设置数据源,接管对象映射文件),配置事务管理器,统一管理,配置事务bean。详细见beans.xml
web.xml中指定spring配置文件,对spring容器实例化
根目录下配置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"
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-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!--数据库信息文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 启用注解扫描 -->
<context:annotation-config/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}"/>
<!-- 连接池的最大值 -->
<property name="maxActive" value="${maxActive}"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}"/>
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="${minIdle}"/>
</bean>
<!-- 配置会话工厂 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 设置数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 接管hibernate对象映射文件 -->
<property name="mappingResources">
<list>
<value>com/yxd/bean/Person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=false
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=false
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
</value>
</property>
</bean>
<!-- 配置事务管理器,统一管理sessionFactory的事务 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 启用事务注解@Transaction -->
<tx:annotation-driven transaction-manager="txManager"/>
<!-- 配置PersonService对象 ,通过注解方式@Resource注入属性值 -->
<bean id="personService" class="com.yxd.service.impl.PersonServiceBean"></bean>
<!-- 配置action,name与struts-config.xml中的action路径一致 -->
<bean name="/person/list" class="com.yxd.web.action.PersonAction"></bean>
</beans>
jdbc.properties文件:
driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/test?useUnicode\=true&characterEncoding\=UTF-8
username=root
password=454831
initialSize=1
maxActive=500
maxIdle=2
minIdle=1
/WEB-INF/web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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_2_5.xsd">
<display-name></display-name>
<!-- 指定spring的配置文件,默认从web根目录寻找配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<!-- 对spring容器进行实例化 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置自己写的过滤器 -->
<!-- <filter> <filter-name>MyFilter</filter-name> <filter class>com.yxd.web.filter.MyFilter</filter-class>
</filter>
<filter-mapping> <filter-name>MyFilter</filter-name> <url-pattern>/*</url-pattern>
</filter-mapping> -->
<!-- 使用spring提供的处理中文乱码的过滤器 -->
<filter>
<filter-name>encoding</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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置opensessioninview解决懒加载
<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>/*</url-pattern>
</filter-mapping>
-->
<!-- 配置struts -->
<servlet>
<servlet-name>struts</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>struts</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
建立junit单元测试,如建包junit.test,放PersonServiceTest.java测试业务方法
3、整合struts
建包com.yxd.web.action,放PersonAction.java,(继承Action类,重写execute方法,使用注解方式注入业务bean(personService),后直接对personService操作)
WEB-INF下建立struts-config.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<action-mappings>
<action path="/person/list" type="com.yxd.web.action.PersonAction"
validate="false">
<forward name="list" path="/WEB-INF/page/personlist.jsp"/>
</action>
</action-mappings>
<!-- 将action作为bean由spring管理,
由ActionServlet交给请求处理器DelegatingRequestProcessor,
请求处理器找action的bean,找不到时才到struts配置文件中 -->
<controller>
<set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor"/>
</controller>
</struts-config>
PersonAction.java:
package com.yxd.web.action;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.yxd.service.PersonService;
public class PersonAction extends Action {
@Resource PersonService personService;
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//WebApplicationContext ctx = WebApplicationContextUtils.
// getWebApplicationContext(this.getServlet().getServletContext());
//PersonService personService = (PersonService) ctx.getBean("personService");
request.setAttribute("persons", personService.getPersons());
return mapping.findForward("list");
}
}
建立WEB-INF/page/personlist.jsp
使用了jstl标签
在jsp文件中加上<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:forEach items="${persons }" var="person">
ID=${person.id},name=${person.name}<br>
</c:forEach>
Person.java: (数据对象类,pojo类也叫javabean)注意:给出无参的构造方法,进行映射
package com.yxd.bean;
public class Person {
private Integer id;
private String name;
public Person(){
}
public Person(String name){
this.name=name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
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="com.yxd.bean">
<class table="person" name="Person">
<cache region="com.yxd.bean.Person" usage="read-write"/>
<id name="id">
<generator class="native"/>
</id>
<property name="name" not-null="true" length="10"/>
</class>
</hibernate-mapping>
PersonService.java:
package com.yxd.service;
import java.util.List;
import com.yxd.bean.Person;
public interface PersonService {
public abstract void save(Person person);
public abstract void update(Person person);
public abstract Person getPerson(Integer personid);
public abstract void delete(Integer personid);
public abstract List<Person> getPersons();
}
PersonServiceBean.java: (业务实现,事务使用注解方式)
package com.yxd.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.yxd.bean.Person;
import com.yxd.service.PersonService;
@Transactional
public class PersonServiceBean implements PersonService {
@Resource private SessionFactory sessionFactory;
public void save(Person person){
sessionFactory.getCurrentSession().persist(person);
}
public void update(Person person){
sessionFactory.getCurrentSession().merge(person);
}
@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
public Person getPerson(Integer personid){
return (Person) sessionFactory.getCurrentSession().get(Person.class, personid);
}
public void delete(Integer personid){
sessionFactory.getCurrentSession().delete(
sessionFactory.getCurrentSession().load(Person.class, personid));
}
@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
@SuppressWarnings("unchecked")
public List<Person> getPersons(){
return sessionFactory.getCurrentSession().createQuery("from Person").list();
}
}
PersonServiceTest.java:
package junit.test;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yxd.bean.Person;
import com.yxd.service.PersonService;
public class PersonServiceTest {
private static PersonService personService;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
personService = (PersonService)applicationContext.getBean("personService");
} catch (RuntimeException e) {
e.printStackTrace();
}
}
@Test
public void testSave() {
personService.save(new Person("小张"));
}
@Test
public void testUpdate() {
Person person = personService.getPerson(1);
//....
person.setName("小丽");
personService.update(person);
}
@Test
public void testGetPerson() {
Person person = personService.getPerson(2);
System.out.println(person.getName());
try {
System.out.println("请关闭数据库");
Thread.sleep(1000*15);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第二次开始获取");
person = personService.getPerson(2);
System.out.println(person.getName());
}
@Test
public void testDelete() {
personService.delete(1);
}
@Test
public void testGetPersons() {
List<Person> persons = personService.getPersons();
for(Person person : persons){
System.out.println(person.getName());
}
}
}