Sprin2.5+Hibernate3.3+Struts2.0.11集成

Sprin2.5+Hibernate3.3+Struts2.0.11集成

1.添加jar文件

Hibernate3.3核心安装包下的
/-----------------------------------/
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\jakaarte-commons\commons-logging.jar、commons-dbcp.jar、commons-pool.jar
lib\aspectj\aspectjweaver.jar 、 aspectjrt.jar
lib\cglib\cglib-nodep-2.1.3.jar
lib\j2ee\common-annoutations.jar
lib\log4j\log4j-1.2.15.jar
/------------------------------------/
数据库驱动

2. 配置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/tx
http://www.springframework.org/schema/tx/spring-tx-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">
<!--导入外部properties -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!--配置数据源 -->
<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" />
<property name="mappingResources">
<list>
<value>cn/soldier/bean/Person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<!-- 指定数据库方言 -->
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</prop>
<!-- 是否根据需要每次自动创建数据库 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- 显示Hibernate持久化操作所生成的SQL -->
<prop key="hibernate.show_sql">true</prop>
<!-- 将SQL脚本进行格式化后再输出 -->
<prop key="hibernate.format_sql">false</prop>

<!-- <prop key="hibernate.cache.use_second_level_cache">true</prop> -->
<!-- <prop key="hibernate.cache.use_query_cache">true</prop> -->
<!-- <prop key="hibernate.provider_class">org.hibernate.cache.EhCacheProvider</prop> -->
</props>
</property>
</bean>

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

<!--启用@Transaction注解的支持- -->
<tx:annotation-driven transaction-manager="txManager" />
<!--使用field方法注入依赖对象 -->
<context:annotation-config />
<!-- -->
<bean id="personService" class="cn.soldier.service.impl.PersonServiceBean"></bean>
</beans>

3.新建实体bean Person
package cn.soldier.bean;
Person.java
public class Person {
private Long id;
private String name;

public Person() {
}

public Person(String name) {
this.name = name;
}

public Person(Long id, String name) {
this.id = id;
this.name = name;
}

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 String toString() {
return "Person [id=" + id + " name=" + name + "]";
}

}
4.建立对应的数据库映射
Person.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">


<hibernate-mapping package="cn.soldier.bean">

<class name="Person" table="person">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
</class>
</hibernate-mapping>

5.建立访问Person实体的Service接口
package cn.soldier.service;

import java.util.List;
import cn.soldier.bean.Person;

public interface PersonService {

public abstract void save(Person person);

public abstract void update(Person person);

public abstract void delete(Long id);

public abstract Person getPerson(Long id);

public abstract List<Person> getPersons();
}

6.建立访问Person实体的Service实现方法
package cn.soldier.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

@Transactional //启用事务管理
public class PersonServiceBean implements PersonService {
@Resource//使用filed注入SessionFactory对象
SessionFactory sessionFactory;

public void save(Person person) {
// 得到容器里面正在被Transaction管理的Session
// 如果使用opeSession(),获得的Session对象是不受Transaction管理的。
Session session = (Session) sessionFactory.getCurrentSession();
session.persist(person);
}

public void update(Person person) {
sessionFactory.getCurrentSession().merge(person);// SaveOrUpdate
}

public void delete(Long id) {
// load方法性能最佳,因为get方法有一个数据装配的过程
sessionFactory.getCurrentSession().delete(
sessionFactory.getCurrentSession().load(Person.class, id));
}

@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)// 不启用事务管理,只读
public Person getPerson(Long id) {
return (Person) sessionFactory.getCurrentSession()
.get(Person.class, id);
}
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
@SuppressWarnings("unchecked")
// 终止警告
public List<Person> getPersons() {
return sessionFactory.getCurrentSession().createQuery("From Person").list();
}
}
7.测试开发好的PersonServiceBean
package junit.test;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

public class PersonServiceBeanTest {
private static PersonService personService;

@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans.xml");
personService = (PersonService) ctx.getBean("personService");

} catch (Exception e) {
e.printStackTrace();
}
}

@Test
public void testSave() {
for (int i = 0; i <10; i++) {
Person person = new Person("逗比---"+i+"---号");
personService.save(person);
}
}

@Test
public void testUpdate() {
Person person = personService.getPerson(1L);
person.setName("逗比2号");
personService.update(person);
System.out.println(personService.getPerson(1L));
}

@Test
public void testDelete() {
personService.delete(2L);
}

@Test
public void testGetPersons() {
for (Person person : personService.getPersons()) {
System.out.println(person);
}
}
}

/*******************************************以上步骤集成了Spring+Hibernate****************************************************/
a.添加jar包
commons-beanutils-1.6.jar
commons-chain-1.1.jar
commons-logging-1.0.4.jar
commons-logging-api-1.1.jar
commons-validator-1.3.0.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
oro-2.0.8.jar
struts2-core-2.0.11.jar
struts2-spring-plugin-2.0.11.jar
struts-core-1.3.5.jar
tiles-api-2.0.4.jar
tiles-core-2.0.4.jar
tiles-jsp-2.0.4.jar
xwork-2.0.4.jar

2.配置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">
<!--在web容器中实例化Spring容器 -->
<!--指定spring的配置文件,默认是从web根目录下寻找配置文件。可以通过spring提供的classpath:前缀指定从类路径下寻找 -->
<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>

<!--在web容器中配置struts2 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

3.配置classpath下的 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>

<!-- 指定Web应用的默认编码集,相当于调用 HttpServletRequest的setCharacterEncoding方法 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<!-- 该 属性指定需要Struts2处理的请求后缀,该属性的默认值是action,即 所有匹配*.action的请求都由Struts 2处理。如
果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开 -->
<constant name="struts.action.extension" value="action" />
<!-- 设 置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好 关闭 -->
<constant name="struts.serve.static.browserCache " value="false" />
<!-- 当 struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生 产环境下使用),开发阶段最好打开 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 开 发模式下使用,这样可以打印出更详细的错误信息 -->
<constant name="struts.devMode" value="true" />
<!-- 默 认的视图主题 -->
<constant name="struts.ui.theme" value="simple" />
<!-- 该 属性指定Struts 2中的action由Spring容器创 建 -->
<constant name="struts.objectFactory" value="spring" />
<package name="person" namespace="/person" extends="struts-default">
<global-results>
<result name="message">/WEB-INF/page/message.jsp</result>
</global-results>
<action name="action_*" class="personList" method="{1}">
<result name="list">/WEB-INF/page/list.jsp</result>
<result name="add">/WEB-INF/page/add.jsp</result>
</action>
</package>
</struts>

4.配置beans.xml
<bean id="personList" class="cn.soldier.web.PersonAction"></bean>

5.添加 list.jap
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri="/struts-tags" prefix="s"%>

<html>
<head>
<title>人员列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

</head>
<s:iterator value="persons">
<s:property value="id" />----<s:property value="name" /><br />
</s:iterator>
<body>
</body>
</html>
6.创建 PersonAction.java

package cn.soldier.web;

import java.util.List;
import javax.annotation.Resource;
import cn.soldier.bean.Person;
import cn.soldier.service.PersonService;

public class PersonAction {
@Resource
PersonService personService;
private String message;
private List<Person> persons;
private Person person;// 负责接收form表单的参数

public String list() {
this.persons = personService.getPersons();
return "list";
}

public String add() {
personService.save(this.person);
this.message = "添加成功";
return "message";
}

public String addUI() {

return "add";
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public List<Person> getPersons() {
return persons;
}

public void setPersons(List<Person> persons) {
this.persons = persons;
}

public Person getPerson() {
return person;
}

public void setPerson(Person person) {
this.person = person;
}
}

7.测试
http://localhost:8080/SSH2/person/action_list.action

8.添加 add.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>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<s:form action="action_add" method="post" namespace="/person">
名称<s:textfield name="person.name"></s:textfield>
<input type="submit" value="提交" />
</s:form>
</body>
</html>
9.添加message.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>My JSP ‘message‘ starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<s:property value="message"/>
</body>
</html>

10.测试
http://localhost:8080/SSH2/person/action_addUI.action

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。