Struts2 + Spring + hibernate 框架搭成实例

时间:2023-03-09 17:21:06
Struts2 + Spring + hibernate 框架搭成实例

1、准备Jar包:

struts2、hibernate、spring所需jar包
struts-core-2.x.x.jar 
----struts核心包
xwork-core-2.x.x.jar
ognl-2.6.x.jar    
----对象导航语言
freemarker-2.3.x.jar  
------struts
2的ui标签的模板使用
commons-fileupload-1.2.x.jar   
----文件上传组件
2.1.6版本后需加入此文件
struts-spring-plugin-2.x.x.jar  
---用于struts
2继承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、 
slf
4j-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
数据库驱动包

mysql-connector-java-bin.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" 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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"> <!-- 1.配置Spring管理 -->
<!-- 将bean交由spring管理可以 用<bean></bean>和扫描加注 -->
<!-- 在xml配置了这个标签后,spring可以自动去扫描base-pack下面或者子包下面的java文件, 如果扫描到有@Component
@Controller@Service等这些注解的类,则把这些类注册为bean 注意:如果配置了<context:component-scan>那么<context:annotation-config/>
标签就可以不用再xml中配置了,因为前者包含了后者。另外<context:annotation-config/>还提供了两个子标签 -->
<!-- 扫描该包及该包下的子包 -->
<context:component-scan base-package="cn.pp" /> <!-- 2.配置数据库连接 -->
<!-- 集成hibernate sessionFactory单例模式 线程安全 创建耗内存 -->
<!-- 数据库的连接池 在xml中配置和数据库相关联,并用c3p0来配置数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8" />
<property name="user" value="root" />
<property name="password" value="" />
<!--初始化时获取的连接数,取值应在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> <!-- 3.配置SessionFactory -->
<bean id="sessionFactory" name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 放置hibernate的配置文件 -->
<property name="mappingResources">
<list>
<value>cn/pp/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> <!-- 4.配置事务 -->
<!--hibernate事务管理器配置 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--spring可以用xml和注解来配置事务 声明 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

3、Spring实例

import java.util.List;

import cn.pp.params.Employee;

public interface EmployeeIService {
public boolean save(Employee employee);
public boolean update(Employee employee);
public Employee find(String userId);
public boolean delete(String... userIds);
public List<Employee> findAll();
}
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.pp.params.Employee;
import cn.pp.service.EmployeeIService; @Service
@Transactional
public class EmployeeServiceImpl implements EmployeeIService {
private static Logger logger = Logger.getLogger(Employee.class);
@Resource(name="sessionFactory")
SessionFactory factory; @Override
public boolean save(Employee employee) {
try {
factory.getCurrentSession().save(employee);
} catch (Exception e) {
logger.error(e.getMessage());
return false;
}
return true;
} @Override
public boolean update(Employee employee) {
try {
factory.getCurrentSession().update(employee);
} catch (Exception e) {
logger.error(e.getMessage());
return false;
}
return true;
} //@Transactional(propagation=Propagation.NOT_SUPPORTED)
@Override
public Employee find(String userId) {
try {
return (Employee)factory.getCurrentSession().get(Employee.class,userId);
} catch (Exception e) {
logger.error(e.getMessage());
}
return null;
} @Override
public boolean delete(String... userIds) {
try {
for (String userId : userIds) {
Employee employee=(Employee)factory.getCurrentSession().load(Employee.class,userId);
factory.getCurrentSession().delete(employee);
}
} catch (Exception e) {
logger.error(e.getMessage());
return false;
}
return true;
} @SuppressWarnings("unchecked")
//@Transactional(propagation=Propagation.NOT_SUPPORTED)
@Override
public List<Employee> findAll() {
try {
//return factory.getCurrentSession().createQuery("from Employee").list();
Criteria criteria=factory.getCurrentSession().createCriteria(Employee.class);
return criteria.list();
} catch (Exception e) {
logger.error(e.getMessage());
}
return null;
} }

数据库表映射文件

<?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>
<class name="cn.pp.params.Employee" table="EMPLOYEE" lazy="true">
<id name="userId" column="USER_ID" type="java.lang.String">
<generator class="uuid" />
</id>
<property name="userName" column="USER_NAME" type="java.lang.String" />
<property name="address" column="ADDRESS" type="java.lang.String" />
<property name="birthday" column="BIRTHDAY" type="java.util.Date" />
</class>
</hibernate-mapping>

测试用例:

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.pp.params.Employee;
import cn.pp.service.EmployeeIService; public class EmployeeIServiceTest { private static EmployeeIService employeeIService; @BeforeClass
public static void initContext() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
employeeIService = (EmployeeIService) context.getBean("employeeServiceImpl");
} @Test
public void testSave() {
Employee e=new Employee();
e.setUserName("杰克");
e.setAddress("北京");
Calendar c = new GregorianCalendar(1991, 5, 5, 0,0,0);
Date date=c.getTime();
e.setBirthday(date);
employeeIService.save(e);
} @Test
public void testUpdate() {
Employee e=employeeIService.find("4028826a507f660001507f6601620000");
e.setUserName("螺丝");
employeeIService.update(e);
} @Test
public void testFind() {
Employee e=employeeIService.find("4028826a507f660001507f6601620000");
System.out.println(e.getUserName());
} @Test
public void testDelete() {
employeeIService.delete("4028826a507f660001507f6601620000");
} @Test
public void testFindAll() {
List<Employee> list=employeeIService.findAll();
for(Employee e : list){
System.out.println(e.getUserName());
employeeIService.delete(e.getUserId());
}
}
}

4、Struts配置:

<struts>
<!-- 指定默认 编码集,作用于HttpServletRequest 的setCharacterEncoding方法和freemarker velocity的输出 -->
<constant name="struts.118n.encoding" value="UTF-8"></constant>
<!-- 该属性用于指定Struts2请求处理的后缀,默认为.action 可以处理所有后缀是.action的处理,如果
需要指定多个请求处理后缀,后缀之间用逗号隔开 -->
<constant name="struts.action.extension" value="do,action"></constant>
<!-- 将struts的action交由spring管理 不在由struts的工厂介入 -->
<constant name="struts.objectFactory" value="spring" /> <package name="employeePackage" namespace="/pg" extends="struts-default" >
<action name="employee_*" class="cn.actions.EmployeeAction" method="{1}">
<result name="message">/WEB-INF/message.jsp</result>
<result name="list">/WEB-INF/list.jsp</result>
</action>
</package>
</struts>

测试实例:

action:

// spring 默认scope 是单例模式    @Scope("prototype") 表示每次接收一个请求创建一个Action对象
@Controller @Scope("prototype")
public class EmployeeAction {
@Resource EmployeeIService employeeIService;
private String message;
private HttpServletRequest request;
private ServletContext context;
private Employee employee; public EmployeeAction(){
request=ServletActionContext.getRequest();
context=ServletActionContext.getServletContext();
}
public String list(){
List<Employee> list=employeeIService.findAll();
request.setAttribute("list", list);
return "list";
}
public String add(){
if(employee!=null){
employeeIService.save(employee);
}else{
setMessage("部分人员信息为空!");
return "message";
}
setMessage("添加成功");
return "message";
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
package cn.pp.params;

import java.util.Date;

public class Employee {
private String userId;
private String userName;
private String address;
private Date birthday;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
} }

list.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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">
</head> <body>
<div><a href="/SSH/index.jsp">添加人员</a></div>
<hr/>
<div>
<c:if test="${list.size()>0 }">
<table>
<thead>
<tr>
<td>用户名</td>
<td>住址</td>
<td>生日</td>
</tr>
</thead>
<tbody>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.userName }</td>
<td>${item.address }</td>
<td>${item.birthday }</td>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
<c:if test="${list.size()==0 }">
<span>暂无数据</span>
</c:if>
</div>
</body>
</html>

add.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!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">
</head> <body>
<div><a href="/SSH/pg/employee_list.do">列表</a></div>
<hr/>
<div>
<form action="/SSH/pg/employee_add.do" method="post">
<table>
<tr>
<td>用户名</td>
<td><input type="text" name="employee.userName" /></td>
</tr>
<tr>
<td>住址</td>
<td><input type="text" name="employee.address" /></td>
</tr>
<tr>
<td>生日</td>
<td><input type="text" name="employee.birthday" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="提交" />
</td>
</tr>
</table>
</form>
</div>
</body>
</html>

message.jsp:

<body>

  		<div>
${message }
</div>
<hr/>
<div>
<a href="/SSH/pg/employee_list.do">返回列表</a>
<a href="/SSH/index.jsp">添加人员</a>
</div>
</body>
</html>