1. Struts2+Spring+Hibernate[非注解开发, extends HibernateDaoSupport]

框架: Struts2+Spring+Hibernate[非注解开发, extends HibernateDaoSupport]

工程结构:

      

一. 创建Web Project工程

  1. 引入jar包

activation.jar, antlr-2.7.6.jar
asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
c3p0-0.9.1.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.apache.log4j-1.2.15.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-collections-3.1.jar
commons-fileupload-1.3.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
freemarker-2.3.19.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
hibernate3.jar
javassist-3.11.0.GA.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
log4j-1.2.17.jar
mail.jar
mysql-connector-java-5.0.4-bin.jar
ognl-3.0.6.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.7.2.jar
spring-aop-3.2.0.RELEASE.jar
spring-aspects-3.2.0.RELEASE.jar
spring-beans-3.2.0.RELEASE.jar
spring-context-3.2.0.RELEASE.jar
spring-core-3.2.0.RELEASE.jar
spring-expression-3.2.0.RELEASE.jar
spring-jdbc-3.2.0.RELEASE.jar
spring-orm-3.2.0.RELEASE.jar
spring-test-3.2.0.RELEASE.jar
spring-tx-3.2.0.RELEASE.jar
spring-web-3.2.0.RELEASE.jar
struts2-core-2.3.15.3.jar
struts2-json-plugin-2.3.15.3.jar
struts2-spring-plugin-2.3.15.3.jar
xwork-core-2.3.15.3.jar

  2. 在src下创建log4j.properties, jdbc.properties

log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=info, stdout

jdbc.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8
jdbc.user = root
jdbc.password =123456

二. 创建数据库和数据表

数据库: shop

数据表: tb_dept, tb_emp

CREATE TABLE `tb_dept` (
  `did` int(11) NOT NULL AUTO_INCREMENT COMMENT '部门id',
  `name` varchar(30) DEFAULT NULL COMMENT '部门名称',
  `addr` varchar(50) DEFAULT NULL COMMENT '部门地址',
  PRIMARY KEY (`did`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

CREATE TABLE `tb_emp` (
  `eid` int(11) NOT NULL AUTO_INCREMENT COMMENT '员工id',
  `username` varchar(20) DEFAULT NULL COMMENT '员工姓名',
  `age` int(11) DEFAULT NULL COMMENT '员工年龄',
  `dept_id` int(11) DEFAULT NULL COMMENT '部门id',
  `did` int(11) DEFAULT NULL,
  PRIMARY KEY (`eid`),
  KEY `FK_ID_TB_DEPT` (`dept_id`),
  KEY `FKCB83DF7739E71C54` (`eid`),
  KEY `FKCB83DF7739E893B8` (`did`),
  CONSTRAINT `FKCB83DF7739E71C54` FOREIGN KEY (`eid`) REFERENCES `tb_dept` (`did`),
  CONSTRAINT `FKCB83DF7739E893B8` FOREIGN KEY (`did`) REFERENCES `tb_dept` (`did`),
  CONSTRAINT `FK_ID_TB_DEPT` FOREIGN KEY (`dept_id`) REFERENCES `tb_dept` (`did`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

三. 配置文件[开发的时候, 先把框架搭好, 在把action/service/dao]

web.xml

<?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"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>shop</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	
	<!-- 配置spring的核心监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 全局初始化参数 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	
	<!-- 配置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>
</web-app>

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.devMode" value="false" />
	
	<package name="shop" extends="struts-default" namespace="/">
		<!-- 部门模块的Action, 自动去找class中的departmentAction(因为action/service/dao都交给spring接管了, 
				这个值对应applicationAction.xml的bean的id) -->
		<action name="department_*" class="departmentAction" method="{1}">
			<result name="findAllDepartments">/WEB-INF/jsp/department/departmentManager.jsp</result>
		</action>
	</package>
</struts>

applicationContext.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.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">

	<!-- 加载资源文件  -->
	<context:property-placeholder location="classpath:jdbc.properties"/>	
	
	<!-- 配合C3P0连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driver}"/>
		<property name="jdbcUrl" value="${jdbc.url}"/>
		<property name="user" value="${jdbc.user}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>
	
	<!-- 配置Hibernate的相关信息 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<!-- 注入dataSource -->
		<property name="dataSource" ref="dataSource"/>
		<!-- 配置Hibernate的其他属性 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.connection.autocommit">false</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
		<!-- 配置Hibernate的配置文件 -->
		<property name="mappingResources">
			<list>
				<value>cn/itcast/shop/hibernateDaoSupportMethodTest/pojo/Department.hbm.xml</value>
				<value>cn/itcast/shop/hibernateDaoSupportMethodTest/pojo/Employee.hbm.xml</value>
			</list>
		</property>
	</bean>
	
	<!-- 事务管理 -->
	<!-- 事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<!-- 注入SessionFactory -->
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	<!-- 开启注解事务 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	<!-- ======================== Action的配置 ======================== -->
	<!-- 部门的Action, 这个id对应struts.xml中Action的class值 -->
	<bean id="departmentAction" class="cn.itcast.shop.hibernateDaoSupportMethodTest.action.DepartmentAction" scope="prototype">
		<!-- 注入departmentService -->
		<property name="departmentService" ref="departmentServiceImpl"/>
	</bean>
	
	<!-- ======================== Service的配置 ======================== -->
	<bean id="departmentServiceImpl" class="cn.itcast.shop.hibernateDaoSupportMethodTest.service.impl.DepartmentServiceImpl">
		<!-- 注入departmentDao -->
		<property name="departmentDao" ref="departmentDaoImpl"/>
	</bean>
	
	<!-- ======================== Dao的配置 ======================== -->
	<bean id="departmentDaoImpl" class="cn.itcast.shop.hibernateDaoSupportMethodTest.dao.impl.DepartmentDaoImpl">
		<!-- 注入sessionFactory -->
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
</beans>

四. 创建POJO类

Department.java

/**
 * 部门POJO
 */
public class Department implements Serializable {
	private static final long serialVersionUID = -6846758285183166255L;
	
	private Integer deptId;			// 编号
	private String name;			// 名称
	private String addr;			// 地址
	
	private Set<Employee> empSet = new HashSet<Employee>();		// 员工集合

     加上 getter/setter }

Employee.java

/**
 * 员工POJO
 */
public class Employee implements Serializable {
	private static final long serialVersionUID = 2406003487145739764L;

	private Integer empId;					// 编号
	private String username;				// 姓名
	private Integer age;					// 年龄
	
	private Department department;			// 部门引用

     加上 getter/setter }

Department.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="cn.itcast.shop.hibernateDaoSupportMethodTest.pojo.Department" table="tb_dept">
		<!-- 主键 -->
		<id name="deptId" type="java.lang.Integer">
			<column name="did"/>
			<generator class="native"/>
		</id>
		
		<!-- 普通字段 -->
		<property name="name" type="java.lang.String">
			<column name="name"/>
		</property>
		<property name="addr" type="java.lang.String">
			<column name="addr"/>
		</property>
		
		<!-- 与员工的关系: one2many -->
		<set name="empSet" table="tb_emp" cascade="delete" inverse="true">
			<key column="eid"/>
			<one-to-many class="cn.itcast.shop.hibernateDaoSupportMethodTest.pojo.Employee"/>
		</set>
	</class>
</hibernate-mapping>

Employee.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="cn.itcast.shop.hibernateDaoSupportMethodTest.pojo.Employee" table="tb_emp">
		<!-- 主键 -->
		<id name="empId" type="java.lang.Integer">
			<column name="eid"/>
			<generator class="native"/>
		</id>
		
		<!-- 普通字段 -->
		<property name="username" type="java.lang.String">
			<column name="username"/>
		</property>
		<property name="age" type="java.lang.Integer">
			<column name="age"/>
		</property>
		
		<!-- 与部门的关系: many2one -->
		<many-to-one name="department" class="cn.itcast.shop.hibernateDaoSupportMethodTest.pojo.Department" column="did" lazy="false"/>
	</class>
</hibernate-mapping>

五. 创建DAO

DepartmentDao.java

package cn.itcast.shop.hibernateDaoSupportMethodTest.dao.impl;

import java.util.List;

import cn.itcast.shop.hibernateDaoSupportMethodTest.pojo.Department;

/**
 * 部门Dao接口
 */
public interface DepartmentDao {

	/**
	 * 查询部门列表
	 * @return 部门列表
	 */
	public List<Department> findAllDepartment();

}

DepartmentDaoImpl.java

package cn.itcast.shop.hibernateDaoSupportMethodTest.dao.impl;

import java.util.List;

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

import cn.itcast.shop.hibernateDaoSupportMethodTest.dao.DepartmentDao;
import cn.itcast.shop.hibernateDaoSupportMethodTest.pojo.Department;

/**
 * 部门Dao接口实现类
 * @author Administrator
 *
 */
public class DepartmentDaoImpl extends HibernateDaoSupport implements DepartmentDao {

	/**
	 * 查询部门列表
	 * @return 部门列表
	 */
	@SuppressWarnings("unchecked")
	public List<Department> findAllDepartment() {
		String hql = "FROM Department";
		return this.getHibernateTemplate().find(hql);
	}
	
}

六. 创建Service

DepartmentService.java

package cn.itcast.shop.hibernateDaoSupportMethodTest.service;

import java.util.List;

import cn.itcast.shop.hibernateDaoSupportMethodTest.pojo.Department;

/**
 * 部门的Service
 */
public interface DepartmentService {

	/**
	 * 查询部门列表
	 * @return 部门列表
	 */
	public List<Department> findAllDepartment();

}

DepartmentServiceImpl.java

package cn.itcast.shop.hibernateDaoSupportMethodTest.service.impl;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import cn.itcast.shop.hibernateDaoSupportMethodTest.dao.DepartmentDao;
import cn.itcast.shop.hibernateDaoSupportMethodTest.pojo.Department;
import cn.itcast.shop.hibernateDaoSupportMethodTest.service.DepartmentService;

/**
 * 部门Service接口实现类
 */
@Transactional
public class DepartmentServiceImpl implements DepartmentService {
	
	// 注入departmentDao
	private DepartmentDao departmentDao;

	/**
	 * 查询部门列表
	 * @return 部门列表
	 */
	public List<Department> findAllDepartment() {
		return departmentDao.findAllDepartment();
	}

	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}
	
}

七. 创建Action

DepartmentAction.java

package cn.itcast.shop.hibernateDaoSupportMethodTest.action;

import java.util.List;

import cn.itcast.shop.hibernateDaoSupportMethodTest.pojo.Department;
import cn.itcast.shop.hibernateDaoSupportMethodTest.service.DepartmentService;

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

/**
 * 部门模块Action
 */
public class DepartmentAction extends ActionSupport implements ModelDriven<Department> {
	private static final long serialVersionUID = -4798405686788642124L;
	
	// 部门引用
	private Department department = new Department();
	
	// 注入departmentService
	private DepartmentService departmentService;

	/**
	 * 查询部门列表
	 * @return 部门列表
	 */
	public String list() {
		// 获取部门列表
		List<Department> departments = departmentService.findAllDepartment();
		
		// 将部门列表放入栈顶
		ActionContext.getContext().getValueStack().set("departments", departments);	
		
		// 返回页面
		return "findAllDepartments";
	}

	// 实现模型驱动, 返回部门引用
	public Department getModel() {
		return department;
	}

	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}
	
}

八. 页面

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>Index</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>
	<h3><a href="${pageContext.request.contextPath }/department_list.action">查询部门列表</a></h3>
</body>
</html>

departmentManager.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<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>
	<h2>部门列表</h2>
	<hr>
	<c:if test="${empty departments }">亲! 没有任何部门信息!</c:if>
	<c:if test="${! empty departments }">
	<form action="" method="post">
		<table border="1px" cellpadding="6" cellspacing="0" width="55%">
			<tr>
				<td style="width: 10%">编号</td>
				<td style="width: 30%">名称</td>
				<td>地址</td>
				<td style="width: 15%">操作</td>
			</tr>
			<c:forEach items="${departments }" var="dept">
				<tr>
					<td>${dept.deptId }</td>
					<td>${dept.name }</td>
					<td>${dept.addr }</td>
					<td><a href="#">编辑</a> | <a href="#">删除</a></td>
				</tr>
			</c:forEach>
		</table>
	</form>
	</c:if>
</body>
</html>

九. 测试[把地址栏中的工程名shop改成shop11运行]

以上是简单的Struts2+Spring+Hibernate框架整合模板, 开发中可作为参考!

 

posted @ 2017-05-13 17:28  半生戎马,共话桑麻、  阅读(210)  评论(0)    收藏  举报
levels of contents