struts2-spring-hibernate实现员工的增删查功能
相信很多朋友都和LZ一样在学习了struts2、hibernate、spring之后都不知道怎么去将三者整合起来用,于是LZ就去查资料看视频,学习了一些简单的使用方法,下面LZ就将这个实例分析给大家。
项目结构:
首先加入spring:
1、加入jar包
2、加入配置文件
1).首先需要引入资源文件(配置的数据库的基本信息(db.properties)----Lz用的mysql)
jdbc.user = root
jdbc.password = mysqladmin
jdbc.driverClass = org.gjt.mm.mysql.Driver
jdbc.jdbcUrl = jdbc:mysql:///springjdbc.initPoolSize = 5
jdbc.maxPoolSize = 10
2).然后需要配置数据源(需要加入c3p0jar包)
3).然后配置sessionFactory
4).最后配置spring的声明式事物
开始写的时候LZ忘记了一件很重要的事情那就是改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_3_0.xsd" id="WebApp_ID" version="3.0"><!-- 配置spring配置文件的名字和位置 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext*.xml</param-value<!--此处的*是通佩符 --></context-param><!-- Bootstraps the root web application context before servlet initialization --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><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>
<?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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:jdbc="http://www.springframework.org/schema/jdbc"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"><!-- 导入资源文件 --><context:property-placeholder location="classpath:db.properties"/><!-- 配置c3p0数据源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="user" value="${jdbc.user}"></property><property name="password" value="${jdbc.password}"></property><property name="driverClass" value="${jdbc.driverClass}"></property><property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property><property name="initialPoolSize" value="${jdbc.initPoolSize}"></property><property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property></bean><!-- 配置sessionFactory --><bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="configLocation" value="classpath:hibernate.cfg.xml"></property><property name="mappingLocations" value="classpath:com_ifox_hh_vo/*.hbm.xml"></property></bean><!-- 配置Spring的声明式事物 --><!-- 1、配置hibernate的事务管理器 --><bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- 2、配置事物属性 --><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="get*" read-only="true"/><tx:method name="*"/></tx:attributes></tx:advice><!-- 3、配置切点 --><aop:config><aop:pointcut expression="execution(* com.ifox.hh.service.*.*(..))" id="txPointcut"/><aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/></aop:config>
</beans>
再加入Hibernate:
1、加入jar包
2、主配置文件(hibernate.cfg.cml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration><session-factory><!-- 配置 hibernate 的基本属性 --><property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property><property name="hibernate.show_sql">true</property><property name="hibernate.format_sql">true</property><property name="hibernate.hbm2ddl.auto">update</property><!-- 配置 hibernate 二级缓存相关的属性. --></session-factory>
</hibernate-configuration>
3、创建实体配置映射文件 生成数据表
需要一个部门的实体类和一个员工的实体类:
部门实体类:
package com_ifox_hh_vo;public class Department {private Integer id;private String departmentName;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getDepartmentName() {return departmentName;}public void setDepartmentName(String departmentName) {this.departmentName = departmentName;}}
生成对应的映射文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2017-4-14 11:11:42 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping><class name="com_ifox_hh_vo.Department" table="SSH_DEPARTMENT"><id name="id" type="java.lang.Integer"><column name="ID" /><generator class="native" /></id><property name="departmentName" type="java.lang.String"><column name="DEPARTMENT_NAME" /></property></class>
</hibernate-mapping>
员工实体类:
package com_ifox_hh_vo;import java.util.Date;public class Employee {private Integer id;//不能被修改private String lastName;private String email;private Date birth;private Date createTime;private Department department;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}public Date getCreateTime() {return createTime;}public void setCreateTime(java.util.Date date) {this.createTime = (Date) date;}public Department getDepartment() {return department;}public void setDepartment(Department department) {this.department = department;}
}
生成对应的映射文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2017-4-14 11:11:42 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping><class name="com_ifox_hh_vo.Employee" table="SSH_EMPLOYEE"><id name="id" type="java.lang.Integer" access="field"><column name="ID" /><generator class="native" /></id><property name="lastName" type="java.lang.String" access="field"><column name="LAST_NAME" /></property><property name="email" type="java.lang.String" access="field"><column name="EMAIL" /></property><property name="birth" type="java.sql.Date" access="field"><column name="BIRTH" /></property><property name="createTime" type="java.sql.Date" access="field"><column name="CREATE_TIME" /></property><many-to-one name="department" class="com_ifox_hh_vo.Department" access="field" fetch="join"><column name="DEPARTMENT" /></many-to-one></class>
</hibernate-mapping>
最后引入struts2:
首先我们先来实现查询员工的功能:
package com.ifox.hh.dao;import org.hibernate.Session;
import org.hibernate.SessionFactory;public class BaseDao {
private SessionFactory sessionFactory;public void setSessionFactory(SessionFactory sessionFactory) {this.sessionFactory = sessionFactory;}public Session getSession() {return this.sessionFactory.getCurrentSession();}
}
2、通过hql进行查询 删除 增加(dao层)
package com.ifox.hh.dao;import java.util.List;import com_ifox_hh_vo.Employee;public class EmployeeDao extends BaseDao{public List<Employee> getAll(){String hql = "FROM Employee e LEFT JOIN FETCH e.department";return getSession().createQuery(hql).list();}public void delete(Integer id){String hql = "DELETE FROM Employee e WHERE e.id=?";getSession().createQuery(hql).setInteger(0, id).executeUpdate();}public void saveOrUpdate(Employee employee){getSession().saveOrUpdate(employee);}
}
package com.ifox.hh.dao;import java.util.List;import com_ifox_hh_vo.Department;public class DepartmentDao extends BaseDao {public List<Department> getAll(){String hql = "FROM Department";return getSession().createQuery(hql).list();}
}
package com.ifox.hh.service;import java.util.List;import com.ifox.hh.dao.EmployeeDao;import com_ifox_hh_vo.Employee;public class EmployeeService{private EmployeeDao employeeDao;public void setEmployeeDao(EmployeeDao employeeDao) {this.employeeDao = employeeDao;}public List<Employee> getAll(){return employeeDao.getAll();}public void delete(Integer id){employeeDao.delete(id);}public void saveOrUpdate(Employee employee){employeeDao.saveOrUpdate(employee);}
}
package com.ifox.hh.service;import java.util.List;import com.ifox.hh.dao.DepartmentDao;import com_ifox_hh_vo.Department;public class DepartmentService {private DepartmentDao departmentDao;public void setDepartmentDao(DepartmentDao departmentDao) {this.departmentDao = departmentDao;}public List<Department> getAll(){return departmentDao.getAll();}
}
下面写struts2的action:
package com_ifox_hh_action;import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;import org.apache.struts2.interceptor.RequestAware;import com.ifox.hh.service.DepartmentService;
import com.ifox.hh.service.EmployeeService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;import com_ifox_hh_vo.Employee;public class EmployeeAction extends ActionSupport implements RequestAware,ModelDriven<Employee>,Preparable{/*** */private static final long serialVersionUID = 1L;private EmployeeService employeeService;private InputStream inputStream;private DepartmentService departmentService;public void setDepartmentService(DepartmentService departmentService) {this.departmentService = departmentService;}public InputStream getInputStream() {return inputStream;}public void setEmployeeService(EmployeeService employeeService) {this.employeeService = employeeService;}//=============================================================//显示所有的员工信息public String list(){request.put("employees", employeeService.getAll());return "list";}private Integer id;public void setId(Integer id) {this.id = id;}//=============================================================//删除员工信息public String delete(){try {employeeService.delete(id);inputStream = new ByteArrayInputStream("1".getBytes("UTF-8"));} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();try {inputStream = new ByteArrayInputStream("0".getBytes("UTF-8"));} catch (UnsupportedEncodingException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}return "delete";}//===========================================================//获取部门信息public String input(){request.put("departments", departmentService.getAll());return INPUT;}//===========================================================//新增员工信息public String save(){model.setCreateTime(new Date());employeeService.saveOrUpdate(model);return SUCCESS;}public void prepareSave(){model = new Employee();}//===========================================================private Map<String, Object>request;@Overridepublic void setRequest(Map<String, Object> arg0) {// TODO Auto-generated method stubthis.request = arg0;}@Overridepublic void prepare() throws Exception {}private Employee model;@Overridepublic Employee getModel() {// TODO Auto-generated method stubreturn model;}}
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.enable.DynamicMethodInvocation" value="false" /><constant name="struts.devMode" value="true" /><package name="default" namespace="/" extends="struts-default"><interceptors><interceptor-stack name="sshStack"><interceptor-ref name="paramsPrepareParamsStack"><param name="prepare.alwaysInvokePrepare">false</param></interceptor-ref></interceptor-stack></interceptors><default-interceptor-ref name="sshStack"></default-interceptor-ref><action name="emp-*" class="employeeAction" method="{1}"><result name="list">/WEB-INF/views/emp-list.jsp</result><result type="stream" name="delete"><param name="contentType">text/html</param><param name="inputName">inputStream</param></result><result name="input">/WEB-INF/views/emp-input.jsp</result><result name="success" type="redirect">/emp-list</result></action></package></struts>
将以上bean都加入到springIOC容器中:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="employeeDao" class="com.ifox.hh.dao.EmployeeDao"><property name="sessionFactory" ref="sessionFactory"></property><!-- 这里两个配置文件都用到了sessionFactory 就是上面web.xml中用到的通配符实现的功能 --></bean><bean id="departmentDao" class="com.ifox.hh.dao.DepartmentDao"><property name="sessionFactory" ref="sessionFactory"></property></bean><bean id="employeeService" class="com.ifox.hh.service.EmployeeService"><property name="employeeDao" ref="employeeDao"></property></bean><bean id="departmentService" class="com.ifox.hh.service.DepartmentService"><property name="departmentDao" ref="departmentDao"></property></bean><bean id="employeeAction" class="com_ifox_hh_action.EmployeeAction"scope="prototype"><property name="employeeService" ref="employeeService"></property><property name="departmentService" ref="departmentService"></property></bean>
</beans>
最后加入jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><a href="emp-list">List Employee info </a><br/><a href="emp-input"> Add Employee </a>
</body>
</html>
2、emp-list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="scripts/jquery-1.11.3.min.js"></script>
<script type="text/javascript">$(function(){$(".delete").click(function(){var $tr = $(this).parent().parent();var lastName = $(this).next(":input").val();var flag = confirm("确定要删除"+lastName+"条信息吗?");if(flag){//使用ajax删除var url = this.href;var args = {"time":new Date()};$.post(url,args,function(data){if(data == "1"){alert("删除成功");$tr.remove();}else{alert("删除失败");}});}return false;});})
</script>
</head>
<body>
<h4>员工列表</h4><s:if test="#request.employees == null || #request.employees.size == 0">没有员工信息
</s:if>
<s:else><table border="1" cellpadding="10" cellspacing="0"><tr><td>ID</td><td>LASTNAME</td><td>EMAIL</td><td>BIRTH</td><td>CREATTIME</td><td>DEPT</td><td>DELETE</td></tr><s:iterator value="#request.employees"><tr><td>${id}</td><td>${lastName }</td><td>${email }</td><td><s:date name="birth" format="yyyy-MM-dd"/></td><td><s:date name="createTime" format="yyyy-MM-dd hh:mm:ss"/></td><td>${department.departmentName}</td><td><a href="emp-delete?id=${id }" class="delete">Delete</a><input type="hidden" value="${lastName }"></td></tr></s:iterator></table>
</s:else>
</body>
</html>
3、emp-input.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><h4>Employee Add page</h4><s:form action="emp-save" method="post"><s:textfield name="lastName" label="LastName"></s:textfield><s:textfield name="email" label="Email"></s:textfield><s:textfield name="birth" label="Birth"></s:textfield><s:select list="#request.departments"listKey="id" listValue="departmentName" name="department.id"label="Department"></s:select><s:submit></s:submit></s:form>
</body>
</html>
下面展示实现效果:
以上便是LZ对ssh整合小例子的初步总结,如果有不对的地方希望指正。
struts2-spring-hibernate实现员工的增删查功能相关推荐
- Struts2+Spring+Hibernate搭建全解!
Struts2+Spring+Hibernate是J2EE的最新流行框架.本篇是我搭建这个框架的经验总结,有很多人搭建这个框架总会遇到 大大小小的问题,网上也没有什么行之有效的方案或成体系的介绍,所以 ...
- Struts2 + Spring + Hibernate 通用 Service 和 DAO
我在 Struts2 + Spring + Hibernate 项目开发中总结出了一个Service 和 DAO ,可以用于处理任何的pojo(bean).使用这两个Service 和 DAO 可以 ...
- SSH之IDEA2017整合Struts2+Spring+Hibernate
摘要 IDEA无疑是Java编程的利器,在下面我们将介绍如何使用IDEA来整合SSH(Struts2 + Spring + Hibernate):介绍將分为三个部分来讲,分别是新建工程,Spring引 ...
- 【struts2+spring+hibernate】ssh框架整合开发
SSH框架整合 1 Struts2+Spring+Hibernate导包 Struts2导入jar包: * struts2/apps/struts2-blank.war/WEB-INF/lib/*.j ...
- java高级框架应用开发案例教程_Java高级框架应用开发案例教程:struts2+spring+hibernate PDF...
资源名称:Java高级框架应用开发案例教程:struts2+spring+hibernate PDF 第1章 struts+spring+hibernate概述 1.1 框架概述 1.2 struts ...
- Java Web项目源代码|CRM客户关系管理系统项目实战(Struts2+Spring+Hibernate)解析+源代码+教程
客户关系管理 (CRM) CRM一般指客户关系管理 客户关系管理是指企业为提高核心竞争力,利用相应的信息技术以及互联网技术协调企业与顾客间在销售.营销和服务上的交互,从而提升其管理方式,向客户提供创新 ...
- Struts2+Spring+Hibernate 三大框架的合并集成
这次来看看Struts2+Spring+Hibernate三大框架的整合应用,主要是Spring和Hibernate框架的整合,因为前边已经将Strtus2+Spring整合过了基本一样. 首先看一下 ...
- Spring、Struts2+Spring+Hibernate整合步骤
所使用的Jar包: Hibernate: Spring(使用MyEclipse自动导入框架功能) Struts2: 注解包和MySql驱动包: 1.配置Hibernate和Spring: <be ...
- 联系人管理-客户拜访记录| CRM客户关系管理系统项目 实战七(Struts2+Spring+Hibernate)解析+源代码
联系人管理-客户拜访记录| CRM客户关系管理系统项目 实战七(Struts2+Spring+Hibernate)解析+源代码 客户拜访记录的列表的显示, 客户拜访记录的保存, 客户拜访记录查询(条件 ...
最新文章
- python networkx绘制图
- 互联网的尽头是乡村振兴
- 用myeclipse搭建S2SH struts2 spring hibernate
- 电信设置的nat 虚拟服务器192.168.1.3 是什么,VMware WorkStation的三种网络连接方式详解...
- 灯泡亮度控制单片机_如何有效保护投影机灯泡 保护投影机灯泡方法【详解】...
- Akka向设备组添加Actor注册《thirteen》译
- 如何编辑SDE数据(转自ESRI中国社区)
- 【Try to Hack】masscan
- OriginPro 绘制柱状图(特别是用于对比实验时)
- 几种通信方式的介绍及详解
- Android开发实用小工具二——长度转换工具
- 常见信息流广告有哪些展现形式
- bzoj4134 ljw和lzr的hack比赛 trie树合并
- 全世界明星都在穿白T?永不发黄,显瘦十斤,两件才99元!
- 好兄弟们,做了份上海落户政策总结给大家看看
- 微信小程序商城 (后台JAVA)
- ElasticSearch(四):ES nested嵌套文档与父子文档处理
- 2017“CCF科学技术奖”全公布,6位获奖人带来独家经验分享
- 编码电位器c语言程序,360°编码电位器原理
- C语言一秒钟看懂for循环和while循环的用法?