[置顶] Spring+Struts2+Hibernate整合

详细的介绍搭建SSH框架环境 ,并用框架实现简单的CRUD操作。

基本需求

概述:完成员工信息的增删改查操作(CRUD),其中员工和部门是单向的多对一关系,在保存和修改页面使用下拉列表实现部门的选择。

图示:

所有员工显示:

保存:
[置顶] Spring+Struts2+Hibernate整合_第1张图片
修改:
[置顶] Spring+Struts2+Hibernate整合_第2张图片

环境搭建:

导入相关jar包

Spring+ Struts2+ Hibernate jar包目录
antlr-2.7.7.jar
asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
c3p0-0.9.1.2.jar
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.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
ehcache-core-2.4.3.jar
freemarker-2.3.19.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.4.Final.jar
hibernate-ehcache-4.2.4.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
log4j-1.2.17.jar
mysql-connector-java-5.1.7-bin.jar
ognl-3.0.6.jar
slf4j-api-1.6.1.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
struts2-core-2.3.15.3.jar
struts2-spring-plugin-2.3.15.3.jar
xwork-core-2.3.15.3.jar

建立基本的包结构,编写配置文件


将包结构建立好后,就可以依据包结构对配置文件进行配置


建立配置文件(二级缓存的文件在优化的时候使用)


编写配置文件

hibernate.cfg.xml
<?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>
        <!-- 配置连接数据库的信息(交给Spring的IOC容器管理) -->

       <!-- 方言 -->
       <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>

       <!-- 其他的配置 -->
       <property name="hibernate.show_sql">true</property>
       <property name="hibernate.format_sql">true</property>
       <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- 映射文件配置 (在IOC容器中管理映射文件,IOC容器中可以进行批量管理) -->
    </session-factory>
</hibernate-configuration>

jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springhibernate
jdbc.user=root
jdbc.password=123456

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

    <!-- 开启包扫描 -->
    <context:component-scan base-package="com.myframe.ssh"></context:component-scan>

    <!-- 引入外部文件(jdbc的配置信息) -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <!-- 配置连接数据库的相关信息 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="jdbcUrl" value="${jdbc.url}"></property>
       <property name="driverClass" value="${jdbc.driverClass}"></property>
       <property name="user" value="${jdbc.user}"></property>
       <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!-- 配置LocalSessionFactoryBean 用于创建一个sessionFactory,ioc容器管理session对象
         这样就可以完成hibernate和Spring整合
     -->
    <bean id="sessionFactory"
        class=" org.springframework.orm.hibernate4.LocalSessionFactoryBean">
       <!-- 使用配置的数据源与数据库建立连接 -->
       <property name="dataSource" ref="dataSource" />
       <!--设置hibernate配置文件的位置-->
       <property name="configLocation" value=" classpath:hibernate.cfg.xml" />
       <!-- 管理每个pojo类的映射文件,使用ioc容器可以实现批量管理 -->
       <property name="mappingLocations">
           <list>
                <value>classpath:com/myframe/ssh/pojo/*.hbm.xml</value>
           </list>
       </property>
    </bean>
    <!-- 配置事务管理器,由ioc容器创建session对象,管理事务 -->
    <bean id="transactionManager"
        class=" org.springframework.orm.hibernate4.HibernateTransactionManager">
       <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 开启基于注解的事务管理 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

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="true" />
     <!--使用增量模式编写action方法和映射-->
    <package name="default" namespace="/" extends="struts-default">

    </package>
</struts>

Spring的IOC容器和Struts2的核心控制器需要在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">

    <!-- 自动创建IOC容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:beans.xml</param-value>
    </context-param>
    <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>

基本的环境配置完成。

编写POJO类,并生成映射文件

测试使用的POJO类(员工和部门类,单向的多对一的关系),并创建映射文件,在设置好的包结构中创建(已经提前配置好映射文件的管理)。
 <property name="mappingLocations">
     <list>
        <value>classpath:com/myframe/ssh/pojo/*.hbm.xml</value>
     </list>
 </property>

Employee
package com.myframe.ssh.pojo;

public class Employee {
    private Integer empId;
    private String empName;
    // 建立单向的多对一关系
    private Department department;

    public Department getDepartment() {
       return department;
    }

    public void setDepartment(Department department) {
       this.department = department;
    }

    public Employee() {
       super();
    }

    public Employee(Integer empId, String empName) {
       super();
       this.empId = empId;
       this.empName = empName;
    }

    public Integer getEmpId() {
       return empId;
    }

    public void setEmpId(Integer empId) {
       this.empId = empId;
    }

    public String getEmpName() {
       return empName;
    }

    public void setEmpName(String empName) {
       this.empName = empName;
    }

    @Override
    public String toString() {
       return "Employee [empId=" + empId + ", empName=" + empName + "]";
    }
}

Employee.hbm.xml
<?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 2016-11-1 18:53:50 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping package="com.myframe.ssh.pojo">
    <class name="Employee" table="T_EMPLOYEE">
        <id name="empId" type="java.lang.Integer">
            <column name="EMP_ID" />
            <generator class=" native" />
        </id>
        <property name="empName" type="java.lang.String">
            <column name="EMP_NAME" />
        </property>
        <many-to-one name="department" class="Department" fetch="join" >
            <column name="DEPT_ID" />
        </many-to-one>
    </class>
</hibernate-mapping>

Department
package com.myframe.ssh.pojo;

public class Department {
    private Integer deptId;
    private String deptName;

    public Department(Integer deptId, String deptName) {
       super();
       this.deptId = deptId;
       this.deptName = deptName;
    }

    public Department() {
       super();
    }

    public Integer getDeptId() {
       return deptId;
    }

    public void setDeptId(Integer deptId) {
       this.deptId = deptId;
    }

    public String getDeptName() {
       return deptName;
    }

    public void setDeptName(String deptName) {
       this.deptName = deptName;
    }

    @Override
    public String toString() {
       return "Department [deptId=" + deptId + ", deptName=" + deptName + "]";
    }
}

Department.hbm.xml
<?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 2016-11-1 18:53:50 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping package="com.myframe.ssh.pojo">
    <class name="Department" table="T_DEPARTMENT">
        <id name="deptId" type="java.lang.Integer">
            <column name="DEPT_ID" />
            <generator class=" native" />
        </id>
        <property name="deptName" type="java.lang.String">
            <column name="DEPT_NAME" />
        </property>
    </class>
</hibernate-mapping>


编写实现CRUD功能

基本接口准备:

Dao 接口
package com.myframe.ssh.dao;

import java.util.List;

import com.myframe.ssh.pojo.Department;
import com.myframe.ssh.pojo.Employee;

public interface EmployeeDao {
    /**
     * 获取所有员工
     *
     * @return 包含所有员工list集合
     */
    public List<Employee> getAllEmp();

    /**
     * 获取所有部门
     *
     * @return 包含所有部门的list集合
     */
    public List<Department> getAllDept();

    /**
     * 获取一个员工
     *
     * @param id
     * @return 一个员工对象
     */
    public Employee getEmp(Integer empId);

    /**
     * 保存一个员工
     *
     * @param employee
     */
    public void saveEmp(Employee employee);

    /**
     * 更新一个员工
     *
     * @param employee
     */
    public void updateEmp(Employee employee);

    /**
     * 删除一个员工
     *
     * @param employee
     */
    public void deleteEmp(Employee employee);

}

Dao接口实现(使用注解自动装配)
package com.myframe.ssh.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.myframe.ssh.pojo.Department;
import com.myframe.ssh.pojo.Employee;

@SuppressWarnings("unchecked")
@Repository
public class EmployeeDaoImpl implements EmployeeDao {
     @Autowired
    private SessionFactory sessionFactory;

    /**
     * 提供一个获取session对象的方法
     *
     * @return session对象
     */
    private Session getSession() {
       return sessionFactory.getCurrentSession();
    }

    @Override
    public List<Employee> getAllEmp() {
       return getSession().createQuery(
               "from Employee e left join fetch e.department").list();
    }

    @Override
    public List<Department> getAllDept() {
       return getSession().createQuery("from Department").list();
    }

    @Override
    public Employee getEmp(Integer EmpId) {
       return (Employee) getSession().get(Employee.class, EmpId);
    }

    @Override
    public void saveEmp(Employee employee) {
       getSession().save(employee);
    }

    @Override
    public void updateEmp(Employee employee) {
       getSession().update(employee);
    }

    @Override
    public void deleteEmp(Employee employee) {
       getSession().delete(employee);
    }

}

Service接口
package com.myframe.ssh.service;

import java.util.List;

import com.myframe.ssh.pojo.Department;
import com.myframe.ssh.pojo.Employee;

public interface EmployeeService {
    /**
     * 获取所有员工
     *
     * @return 包含所有员工list集合
     */
    public List<Employee> getAllEmp();

    /**
     * 获取所有部门
     *
     * @return 包含所有部门的list集合
     */
    public List<Department> getAllDept();

    /**
     * 获取一个员工
     *
     * @param id
     * @return 一个员工对象
     */
    public Employee getEmp(Integer EmpId);

    /**
     * 保存一个员工
     *
     * @param employee
     */
    public void saveEmp(Employee employee);

    /**
     * 更新一个员工
     *
     * @param employee
     */
    public void updateEmp(Employee employee);

    /**
     * 删除一个员工
     *
     * @param employee
     */
    public void deleteEmp(Integer empId);

}

Service接口实现(使用注解配置事务)
package com.myframe.ssh.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.myframe.ssh.dao.EmployeeDao;
import com.myframe.ssh.pojo.Department;
import com.myframe.ssh.pojo.Employee;

@Transactional
@Service
public class EmployeeServiceImpl implements EmployeeService {
     @Autowired
    private EmployeeDao employeeDao;

    @Transactional(readOnly = true)
    @Override
    public List<Employee> getAllEmp() {
       return employeeDao.getAllEmp();
    }

    @Transactional(readOnly = true)
    @Override
    public List<Department> getAllDept() {
       // TODO Auto-generated method stub
       return employeeDao.getAllDept();
    }

    @Transactional(readOnly = true)
    @Override
    public Employee getEmp(Integer EmpId) {
       return employeeDao.getEmp(EmpId);
    }

    @Override
    public void saveEmp(Employee employee) {
       System.out.println(employee);
       employeeDao.saveEmp(employee);
    }

    @Override
    public void updateEmp(Employee employee) {
       employeeDao.updateEmp(employee);
    }

    @Override
    public void deleteEmp(Integer empId) {
       Employee emp = employeeDao.getEmp(empId);
       if (emp != null) {
           employeeDao.deleteEmp(emp);
       }
    }

}

对编写的接口进行测试(测试的时候创建数据库表)

编写action(CRUD)---使用增量式编码的方式对代码进行补充

    根据流程编写对应的action
    编写页面:index.jsp,   list.jsp,   save.jsp,   update.jsp           

查询所有员工                

实现步骤:
①页面发出请求getAll.action
<a href="${pageContext.request.contextPath }/getAll.action">查询所有员工</a>
②struts.xml配置action(要由框架帮我们管理请求)
<action name="getAll" class="com.myframe.ssh.action.EmployeeAction" method="getAll">
           <result>list.jsp</result>
</action>
③写处理action的方法(注:要想在页面获取某域中的数据必须实现XxxAware)
在准备好的包结构中创建一个专门来管理所有action方法的类
@Controller
@Scope("prototype")
public class EmployeeAction{

    @Autowired
    private EmployeeService employeeService;
  
}
添加一个获取所有员工的action
package com.myframe.ssh.action;

import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.myframe.ssh.pojo.Department;
import com.myframe.ssh.pojo.Employee;
import com.myframe.ssh.service.EmployeeService;

@Controller
@Scope("prototype")
public class EmployeeAction implements RequestAware {

    @Autowired
    private EmployeeService employeeService;
    private Map<String, Object> request;

    public String getAll() {
       // 要想保存到request中必须实现RequestAware
       // 要想在页面获取必须实现XxxAware
       List<Employee> empList = employeeService.getAllEmp();
       request.put("empList", empList);
       return "success";
    }

    @Override
    public void setRequest(Map<String, Object> request) {
       this.request = request;
    }

}
④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>
</head>
<body>
    <h1 align="center">显示所有员工信息</h1>
    <s:if test="#request.empList == null || #request.empList.empty">
       没有员工信息
    </s:if>

    <s:else>
       <center>
           <table border="1" width="80%">
               <tr>
                  <th>ID</th>
                  <th>员工姓名</th>
                  <th>部门名称</th>
                  <th>修改</th>
                  <th>删除</th>
               </tr>
                <s:iterator value="#request.empList">
                  <tr>
                      <td><s:property value="empId"/></td>
                      <td><s:property value="empName"/></td>
                       <td><s:property value="department.deptName"/></td>
                      <td><s:a action="#">修改</s:a></td>
                      <td><s:a action="#">删除</s:a></td>
                  </tr>
               </s:iterator>
           </table>
       </center>
    </s:else>
       <center>
       <!-- 到添加页面,需要向页面传递一些信息,因此需要发送请求 -->
       <a href="#">添加</a>
       </center>
</body>
</html>
 测试

保存一名员工

步骤:
 ①从list.jsp页面发送tosave.action(保存前做一些准备工作)
<a href="${pageContext.request.contextPath }/tosave.action">添加</a>
 ②配置action
 <!-- 向保存页面传递一些部门信息 -->
<action name="tosave" class="com.myframe.ssh.action.EmployeeAction" method="tosave">
     <!-- 到保存页面 -->
     <result name="save">save.jsp</result>
</action>
③写处理action的方法(注:表单要可以显示部门的下拉列表,可以供选择)
    public String tosave() {
       List<Department> deptList = employeeService.getAllDept();
       request.put("deptList", deptList);
       return "save";
    }
到save.jsp页面,填写信息,然后提交表单(注意:下拉列选的设置),发送 dosave.action请求
    <h1 align="center">添加员工</h1>
    <!-- action 路径从当前项目开始 -->
    <s:form action="dosave">
       <s:textfield name="empName" label="员工姓名"/>
        <s:select list="#request.deptList" label="部门" listKey="deptId" listValue="deptName" name="department.deptId" ></s:select>
       <s:submit value="保存"></s:submit>
    </s:form>
⑤ 配置dosave.action
<action name="dosave" class="com.myframe.ssh.action.EmployeeAction" method="dosave">
       <!--重定向到list.jsp-->
       <result type="redirectAction" name="list">
           <param name="actionName">getAll</param>
           <param name="namespace">/</param>
       </result>
</action>
 ⑥编写 dosave的方法(使用模型对象接收表单提交的数据)

实现 ModelDriven<T>接口, Preparable接口(使用模型驱动封装表单数据)
public class EmployeeAction implements RequestAware, ModelDriven<Employee>,
       Preparable
     声明模型对象
    //模型对象,我们需要提前给模型对象赋初始值
    private Employee employee;
    
    /**
     * 框架会将表单提交的数据自动封装到我们准备的模型对象中(使用参数拦截器),同时也可以在页面获取模型对象中的值(因为getModel将模型对象保存在对象栈中)
     * 将模型对象压入栈中,注:对象不能是null,若是null不进行压栈工作
     * 因为getModel方法每次处理请求之前都会执行,因此不在这个方法中给模型对象赋值 使用前缀方法
     */
    @Override
    public Employee getModel() {
       return employee;
    }

    /**
     * 它也是每个请求都会执行,因此也不在这个里面赋值
     */
    @Override
    public void prepare() throws Exception {
       System.out.println("prepare....");
    }
    使用前缀方法给模型对象赋值
    public void prepareDosave() {
       employee = new Employee();
    }
    这样框架就会自动将我们从表单提交的数据封装到模型对象上,我们只需要保存这个对象即可。
    public String dosave() {
       employeeService.saveEmp(employee);
       return "list";
    }

修改一名员工

步骤:
①从list.jsp页面发送toupdate.action(这个操作是给update.jsp回显一些信息)
<td><s:a action="toupdate?empId=%{empId}">修改</s:a></td>
②配置action
<action name="toupdate" class="employeeAction" method="toupdate">
     <result name="update">update.jsp</result>
</action>
③编写action方法
     //属性驱动
     private Integer empId;

    /**
     * 需要在前缀方法执行之前,执行参数拦截器
     */
    public void prepareToupdate() {
       employee = employeeService.getEmp(empId);
    }

    public String toupdate() {
       List<Department> deptList = employeeService.getAllDept();
       request.put("deptList", deptList);
       return "update";
    }
     
    public Integer getEmpId() {
       return empId;
    }

    public void setEmpId(Integer empId) {
       this.empId = empId;
    }
    getModel() 
    getModel方法可以将前缀方法准备的对象压入对象栈,这样在页面就可以获取到
      需要在执行前缀方法前执行参数拦截器,给empId赋值
      需要在struts.xml中配置拦截器栈
<default-interceptor-ref name="paramsPrepareParamsStack"/>
 ④update.jsp
    <h1 align="center">修改员工</h1>
    <s:form action="doupdate">
       <s:hidden name="empId"/>
       <s:textfield name="empName" label="员工姓名"/>
       <s:select list="#request.deptList" listKey="deptId" listValue="deptName" label="部门名称" name="department.deptId"></s:select>
       <s:submit value="修改"></s:submit>
    </s:form>
修改后,提交doupdate.action,保存修改信息
      <action name="doupdate" class="employeeAction" method="doupdate">
           <result type="redirectAction" name="list">getAll</result>
       </action>
 ⑥真正执行保存的action
    public void prepareDoupdate() {
       employee = new Employee();
       //employee = employeeService.getEmp(empId);
    }

    public String doupdate() {
        employeeService.updateEmp(employee);;
       return "list";
    }
    getModel()会将模型对象压栈,参数拦截器完成将表单数据包装成模型对象

总结:保存和修改操作都需要发送两次请求,原因是在执行保存和修改操作前,编辑页面需要从数据库获取一些信息在页面显示。

删除一名员工

步骤:
① list.jsp页面发送delete.action
     list.jsp
<td><s:a action="delete?empId=%{empId}">删除</s:a></td>
 ②配置action
    <action name="delete" class="employeeAction" method="delete">
           <result type="redirectAction" name="list">getAll</result>
    </action>
 ③ 编写action方法
    public String delete() {
       employeeService.deleteEmp(empId);
       return "list";
    }
          

 完整action类

package com.myframe.ssh.action;

import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.myframe.ssh.pojo.Department;
import com.myframe.ssh.pojo.Employee;
import com.myframe.ssh.service.EmployeeService;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

@Controller
@Scope("prototype")
public class EmployeeAction implements RequestAware, ModelDriven<Employee>,
       Preparable {

    @Autowired
    private EmployeeService employeeService;
    private Map<String, Object> request;
    private Employee employee;

    private Integer empId;


    public String delete() {
       employeeService.deleteEmp(empId);
       return "list";
    }

    public void prepareDoupdate() {
       //employee = new Employee();
       employee = employeeService.getEmp(empId);
    }

    public String doupdate() {
        employeeService.updateEmp(employee);;
       return "list";
    }

    /**
     * 需要在前缀方法执行之前,执行参数拦截器
     */
    public void prepareToupdate() {
       employee = employeeService.getEmp(empId);
    }

    public String toupdate() {
       List<Department> deptList = employeeService.getAllDept();
       request.put("deptList", deptList);
       return "update";
    }

    public void prepareDosave() {
       employee = new Employee();
    }

    // 保存功能使用模型驱动
    public String dosave() {
       employeeService.saveEmp(employee);
       return "list";
    }

    public String tosave() {
       List<Department> deptList = employeeService.getAllDept();
       request.put("deptList", deptList);
       return "save";
    }

    public String getAll() {
       // 要想保存到request中必须实现RequestAware
       // 要想在页面获取必须实现XxxAware
       List<Employee> empList = employeeService.getAllEmp();
       request.put("empList", empList);
       return "success";
    }

    @Override
    public void setRequest(Map<String, Object> request) {
       this.request = request;
    }

    /**
     * 框架会将表单提交的数据自动封装到我们准备的模型对象中(使用参数拦截器),同时也可以在页面获取模型对象中的值(它使用getModel保存在对象栈中)
     * 将模型对象压入栈中,注:对象不能是null,若是null不进行压栈工作
     * 因为getModel方法每次处理请求之前都会执行,因此不在这个方法中给模型对象赋值 使用前缀方法
     */
    @Override
    public Employee getModel() {
       return employee;
    }

    /**
     * 它也是每个请求都会执行,因此也不在这个里面赋值
     */
    @Override
    public void prepare() throws Exception {
       System.out.println("prepare....");
    }

    public Integer getEmpId() {
       return empId;
    }

    public void setEmpId(Integer empId) {
       this.empId = empId;
    }

}

完整action映射

<?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="true" />

    <!-- 这里的class可以直接使用类名首字母小写 -->
    <package name="default" namespace="/" extends="struts-default">
       <default-interceptor-ref name="paramsPrepareParamsStack"/>
       <action name="getAll" class="com.myframe.ssh.action.EmployeeAction" method="getAll">
           <result>list.jsp</result>
       </action>
       <!-- 向保存页面传递一些部门信息 -->
       <action name="tosave" class="com.myframe.ssh.action.EmployeeAction" method="tosave">
           <!-- 到保存页面 -->
           <result name="save">save.jsp</result>
       </action>
       <action name="dosave" class="com.myframe.ssh.action.EmployeeAction" method="dosave">
           <result type="redirectAction" name="list">
               <param name="actionName">getAll</param>
               <param name="namespace">/</param>
           </result>
       </action>


       <action name="toupdate" class="employeeAction" method="toupdate">
           <result name="update">update.jsp</result>
       </action>

       <action name="doupdate" class="employeeAction" method="doupdate">
           <result type="redirectAction" name="list">getAll</result>
       </action>

       <action name="delete" class="employeeAction" method="delete">
           <result type="redirectAction" name="list">getAll</result>
       </action>

    </package>
</struts>

二级缓存配置

可以配置一个二级缓存对性能进行优化(hibernate配置文件中配置)
<!-- 使用二级缓存 -->
       <property name="hibernate.cache.use_second_level_cache">true</property>
       <!-- 配置一个缓存工厂组件 -->
       <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
       <!-- 指定那些类使用二级缓存 -->
       <class-cache usage="read-only" class="com.myframe.ssh.pojo.Department"/>


SSH框架搭建完成,CRUD功能完成!!!

你可能感兴趣的:(ssh框架整合,实现增删改查,二级缓存配置)