您的位置:首页 > 编程语言 > Java开发

struts2-spring-hibernate实现员工的增删查功能

2017-04-19 10:02 656 查看
相信很多朋友都和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:///spring

jdbc.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:// 4000
www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd 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-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://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:

1、同样的先引入jar包
2、然后加入struts2配置文件struts.xml
由于还没有写需要实现的功能所以暂时不附上代码,等后面写了功能之后再附上代码

首先我们先来实现查询员工的功能:

1).获取session
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();
}
}


3、service层
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 block
e.printStackTrace();
try {
inputStream = new ByteArrayInputStream("0".getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.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;

@Override
public void setRequest(Map<String, Object> arg0) {
// TODO Auto-generated method stub
this.request = arg0;
}

@Override
public void prepare() throws Exception {}
private Employee model;

@Override
public Employee getModel() {
// TODO Auto-generated method stub
return 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"></p
ac17
roperty>
</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页面:
1、index.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整合小例子的初步总结,如果有不对的地方希望指正。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: