struts2+spring+hibernate整合步骤

color=red]一步:[/color]
[quote]
struts2、hibernate、spring所需jar包

struts-core-2.x.x.jar ----struts核心包
xwork-core-2.x.x.jar -----身体ruts在其撒很难过构建
ognl-2.6.x.jar ----对象导航语言
freemarker-2.3.x.jar ------struts2的ui标签的模板使用
commons-fileupload-1.2.x.jar ----文件上传组件 2.1.6版本后需加入此文件
struts-spring-plugin-2.x.x.jar ---用于struts2继承spring的插件

hibernate核心安装包下的(下载路径:http://www.hibernate.org/ ,点击Hibernate Core 右边的download)
hibernate2.jar
lib\bytecode\hibernate-cglib-repack-2.1_3.jar
lib\required\*.jar
hibernate安装包下的(下载路径:http://www.hibernate.org/;点击Hibernate Annotations 右边的下载)
hibernate-annotations.jar
lib\ejb3-persistence.jar、hibernate-commons-annotations.jar
hibernate针对JPA的实现包(下载路径:http://www.hibernate.org/ ,点击Hibernate Entitymanager右边下载)
hibernate-entitymanager.jar
lib\test\log4j.jar、 slf4j-log4j12.jar

spring安装包下的
dist\spring.jar
lib\c3p0\c3p0-0.9.1.2.jar
lib\aspecti\aspectjweaver.jar
aspectjrt.jar
lib\colib\cglib-nodep-2.1_3.jar
lib\j2ee\common-annotations.jar
vlib\log4j\log4j-1.2.15.jar
lib\jakarta-commons\commons_loggin.jar

数据库驱动包
[/quote]
[quote]
创建mysql数据库ssh 设置编码为utf-8 语句:
create database ssh character set 'utf8' collate 'utf8_general_ci'
[/quote]
[quote]
1.先整合spring和hibernate
*将spring和hibernate的jar包放入lib下;
*创建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">

<!-- 将bean交由spring管理可以 用<bean></bean>和扫描加注 -->
<!--
扫描该包及该包下的子包
-->
<context:component-scan base-package="com.yss"></context:component-scan>


<!-- 集成hibernate sessionFactory单例模式 线程安全 创建耗内存-->
<!-- 将hibernate的事务也交由spring管理 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="org.gjt.mm.mysql.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=UTF-8" />
<property name="user" value="root" />
<property name="password" value="root" />
<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="1" />
<!--连接池中保留的最小连接数。-->
<property name="minPoolSize" value="1" />
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="300" />
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="60" />
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="5" />
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="60" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources"><!-- 放置hibernate的配置文件 -->
<list>
<value>com/yss/bean/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false
</value>
</property>
</bean>

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

<!--spring可以用xml和注解来配置事务 声明 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

*配置hibernate的model.hbm.xml和创建model类
*创建service
service接口:
public interface EmployeeService {
public boolean save(Employee employee);
public boolean update(Employee employee);
public Employee find(String username);
public boolean delete(String... username);//表示可变参数
public List<Employee> findAll();
}

service实现类:
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.yss.bean.Employee;
import com.yss.service.EmployeeService;

/**
* @author qing 默认bean名称 employeeServiceBean
*@Service @Transactional 注入service和开启事务
*/
@Service
@Transactional
public class EmployeeServiceBean implements EmployeeService {
private static Logger logger = Logger.getLogger(Employee.class);
/**
* 注入sessionFactory
*/
@Resource SessionFactory factory;

public boolean delete(String... usernames) {
try {
for (String username : usernames) {
factory.getCurrentSession().delete(
factory.getCurrentSession().load(Employee.class,
username));
}
} catch (Exception e) {
logger.error(e.getMessage());
return false;
}
return true;
}

/*
* (non-Javadoc)
*
* @see com.yss.service.EmployeeService#find(com.yss.bean.Employee)
* 此标注表示不需要事务处理
*/
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public Employee find(String username) {
return (Employee) factory.getCurrentSession().get(Employee.class,
username);
}

@SuppressWarnings("unchecked")
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public List<Employee> findAll() {
return factory.getCurrentSession().createQuery("from Employee emp")
.list();
}

public boolean save(Employee employee) {
try {
factory.getCurrentSession().persist(employee);// .save(employee);//
// 获取已经开好的Session
} catch (Exception e) {
logger.error(e.getMessage());
return false;
}
return true;
}

public boolean update(Employee employee) {
try {
factory.getCurrentSession().merge(employee);// 类似于saveOrUpdate()方法
} catch (Exception e) {
logger.error(e.getMessage());
return false;
}
return true;
}

}

*新建测试类
public class EmployeeTest {
private static EmployeeService employeeService;

@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ApplicationContext context = new ClassPathXmlApplicationContext(
"beans.xml");
employeeService = (EmployeeService) context
.getBean("employeeServiceBean");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

@Test
public void createTable() {
//new ClassPathXmlApplicationContext("beans.xml");
};

@Test
public void save() {
boolean result=employeeService.save(new Employee("long","long"));
if (result) {
System.out.println("保存成功。。。。。");
}else{
System.out.println("保存出错....");
}
};

@Test
public void delete() {
boolean result=employeeService.delete("long");
if (result) {
System.out.println("删除成功。。。。。");
}else{
System.out.println("删除出错....");
}
};

@Test
public void update() {
boolean result=employeeService.update((new Employee("qing","long")));
if (result) {
System.out.println("更新成功。。。。。");
}else{
System.out.println("更新出错....");
}
};

@Test
public void findAll() {
List<Employee> elist=employeeService.findAll();
Iterator itor=elist.iterator();
while(itor.hasNext()){
Employee emp=(Employee)itor.next();
System.out.println(emp.getPassword());
}
};

@Test
public void find(){
Employee employee=employeeService.find("qing");
System.out.println(employee.getPassword());
}
}

*ok 没问题spring和hibernate整合完毕

*再将struts2所需包加入lib中
*创建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>
<!-- 将struts的action交由spring管理 不在由struts的工厂介入 -->
<constant name="struts.objectFactory" value="spring" />

<package name="employee" namespace="/employee" extends="struts-default">
<action name="list" class="employeeAction">
<result name="success">
/WEB-INF/feapp/employee.jsp
</result>
</action>

<action name="manager_*" class="employeeManagerAction" method="{1}">
<result name="success">
/WEB-INF/feapp/employeeadd.jsp
</result>
<result name="message">
/WEB-INF/feapp/result.jsp
</result>
</action>
</package>
</struts>

*在web.xml中加入
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<!--
指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value><!-- 多个配置文件的写法 classpath:beans1.xml,classpath:beans2.xml,classpath:beans3.xml -->
</context-param>
<!-- 对Spring容器进行实例化 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- struts2 的监听器 -->
<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>

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

*创建相关jsp和action

@Controller @Scope("prototype")
public class EmployeeManagerAction extends ActionSupport {
@Resource EmployeeService employeeService;
private Employee employee;

public String addUI(){
//System.out.println("user come");
return SUCCESS;
}

public String add(){
//System.out.println("--------------");
boolean result=employeeService.save(employee);
//ActionContext.getContext().put("genders", Gender.values());
if(result){
ActionContext.getContext().put("message", "保存成功!");
}else{
ActionContext.getContext().put("message", "保存失败!");
}
return "message";
}

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}
}


spring+struts2+hibernate的jar包:

[/quote]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值