完成上面的雇员管理系统的相关功能:
<a href="#">添加雇员</a>
<a href="#">删除雇员</a>
<a href="#">修改雇员</a>
<a href="#">退出系统</a>
首先完成添加雇员功能:
登陆成功后,显示mainframe.jsp:
<body> <h2>欢迎 ${loginer.name} 所在部门: ${loginer.department.name}请选择你要的操作</h2> <a href="${pageContext.request.contextPath}/employee.do?flag=addEmpUi">添加雇员</a> <a href="#">删除雇员</a> <a href="#">修改雇员</a> <a href="#">退出系统</a> </body>
点击添加雇员,调用EmployeeAction的addEmpUi方法,显示雇员添加页面
编写EmployeeAction:package com.cdtax.web.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import com.cdtax.domain.Employee; import com.cdtax.web.forms.EmployeeForm; public class EmployeeAction extends DispatchAction { public ActionForward addEmpUi(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //打通流程 return mapping.findForward("goAddEmp"); } //处理添加雇员的请求 public ActionForward addEmp(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //看看这里是否能够得到用户提交的各种数据 EmployeeForm employeeForm = (EmployeeForm)form; // System.out.println(employeeForm.getDepartmentId() + " |" + // employeeForm.getEmail() + " |" + employeeForm.getGrade() // + " |" + employeeForm.getName() + " |" + employeeForm.getPwd() // + " |" + employeeForm.getSalary()); return null; } }相应的雇员添加页面和对应的form
<%@ 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>My JSP 'addemp.jsp' starting page</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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> 添加雇员页面 <br> <form action="${pageContext.request.contextPath}/employee.do?flag=addEmp" method="post"> <table> <tr><td>name</td><td><input type="text" name="name" /></td></tr> <tr><td>email</td><td><input type="text" name="email" /></td></tr> <tr><td>grade</td><td><input type="text" name="grade" /></td></tr> <tr><td>pwd</td><td><input type="text" name="pwd" /></td></tr> <tr><td>salary</td><td><input type="text" name="salary" /></td></tr> <tr><td>department</td> <td> <select name="departmentId"> <option value="1">财务部</option> <option value="2">人事部</option> </select> </td> </tr> <tr><td><input type="submit" value="添加" /></td> <td><input type="reset" value="重置" /></td></tr> </table> </form> </body> </html>
package com.cdtax.web.forms; import org.apache.struts.action.ActionForm; public class EmployeeForm extends ActionForm { private String id; private String pwd; private String email; private String grade; private String name; private String salary; private String departmentId; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } public String getDepartmentId() { return departmentId; } public void setDepartmentId(String departmentId) { this.departmentId = departmentId; } public String getId() { return id; } public void setId(String id) { System.out.println("form id" + id); this.id = id; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <form-beans> <form-bean name="employeeForm" type="com.cdtax.web.forms.EmployeeForm" /> </form-beans> <action-mappings> <action path="/login" parameter="flag" name="employeeForm"> <forward name="ok" path="/WEB-INF/mainFrame.jsp" /> <forward name="err" path="/WEB-INF/login.jsp" /> </action> <!-- 配置employeeAction --> <action path="/employee" name="employeeForm" parameter="flag"> <forward name="goAddEmp" path="/WEB-INF/addemp.jsp" /> </action> </action-mappings> <!-- 配置代理请求处理 DelegatingRequestProcessor它的用处是 --> <controller> <set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor" /> </controller> </struts-config>因为spring接管了struts的action,所以spring配置文件中增加
这里只是将流程走通,没有进行数据库添加操作,EmployeeAction的addEmp方法只是打印出前台提交的数据。
修改EmployeeAction的addEmp方法,进行数据库存取操作
从雇员添加页面获取的信息被封装到EmployeeForm中,然后生成一个雇员对象Employee,根据form设置相关值,然后保存,这里涉及到部门信息的取得,因为Employee对象中有一个Department,所以修改DepartmentServiceInter,增加一个根据id获取部门对象的方法:
package com.cdtax.service.interfaces; import com.cdtax.domain.Department; public interface DepartmentServiceInter { //保存部门的方法 public void addDepartment(Department d); //根据id获取部门 public Department getDepartmentById(java.io.Serializable id); }
package com.cdtax.service.impl; import java.io.Serializable; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.transaction.annotation.Transactional; import com.cdtax.domain.Department; import com.cdtax.service.interfaces.DepartmentServiceInter; @Transactional public class DepartmentService implements DepartmentServiceInter { @Resource private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public SessionFactory getSessionFactory() { return sessionFactory; } public void addDepartment(Department d) { sessionFactory.getCurrentSession().save(d); } public Department getDepartmentById(Serializable id) { return (Department)sessionFactory.getCurrentSession().get(Department.class,id); } }
package com.cdtax.web.action; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import com.cdtax.domain.Employee; import com.cdtax.service.interfaces.DepartmentServiceInter; import com.cdtax.service.interfaces.EmployeeServiceInter; import com.cdtax.web.forms.EmployeeForm; public class EmployeeAction extends DispatchAction { @Resource private DepartmentServiceInter departmentService; @Resource private EmployeeServiceInter employeeService; public void setDepartmentService(DepartmentServiceInter departmentService) { this.departmentService = departmentService; } public void setEmployeeService(EmployeeServiceInter employeeService) { this.employeeService = employeeService; } public ActionForward addEmpUi(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //打通流程 return mapping.findForward("goAddEmp"); } //处理添加雇员的请求 public ActionForward addEmp(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //看看这里是否能够得到用户提交的各种数据 EmployeeForm employeeForm = (EmployeeForm)form; // System.out.println(employeeForm.getDepartmentId() + " |" + // employeeForm.getEmail() + " |" + employeeForm.getGrade() // + " |" + employeeForm.getName() + " |" + employeeForm.getPwd() // + " |" + employeeForm.getSalary()); //创建一个Employee对象,DAO Employee employee = new Employee(); employee.setEmail(employeeForm.getEmail()); employee.setGrade(Integer.parseInt(employeeForm.getGrade())); employee.setHiredate(new java.util.Date()); employee.setName(employeeForm.getName()); employee.setPwd(employeeForm.getPwd()); employee.setSalary(Float.parseFloat(employeeForm.getSalary())); //该雇员是哪个部门的 employee.setDepartment(departmentService.getDepartmentById(Integer.parseInt(employeeForm.getDepartmentId()))); //保存雇员 try { employeeService.addEmployee(employee); } catch (Exception e) { return mapping.findForward("opererr"); } return mapping.findForward("operok"); } }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <form-beans> <form-bean name="employeeForm" type="com.cdtax.web.forms.EmployeeForm" /> </form-beans> <action-mappings> <action path="/login" parameter="flag" name="employeeForm"> <forward name="ok" path="/WEB-INF/mainFrame.jsp" /> <forward name="err" path="/WEB-INF/login.jsp" /> </action> <!-- 配置employeeAction --> <action path="/employee" name="employeeForm" parameter="flag"> <forward name="goAddEmp" path="/WEB-INF/addemp.jsp" /> </action> </action-mappings> <!-- 配置全局跳转 --> <global-forwards> <forward name="opererr" path="/WEB-INF/opererr.jsp"></forward> <forward name="operok" path="/WEB-INF/operok.jsp"></forward> </global-forwards> <!-- 配置代理请求处理 DelegatingRequestProcessor它的用处是 --> <controller> <set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor" /> </controller> </struts-config>
目前这个项目的代码复用性不好,我们需要重新整理.
通过在web层和业务层间增加了一套基础接口来提高代码的复用性.如Employee和Department的service都有一个添加和根据id查找的方法,怎样整合呢
搞一个BasicServiceInter接口:基础接口,EmployeeServiceInter和DepartmentServiceInter都继承自基础接口BasicServiceInter,普通的业务实现类实现相应接口
创建基础接口的抽象类BasicService,实现BasicServiceInter接口,同时普通业务处理类继承次抽象类。
创建基础接口:
package com.cdtax.basic; import java.util.List; public interface BasicServiceInter { //声明一些常用的方法 //1.通过id获取对象 public Object findById(Class clazz,java.io.Serializable id); //2.查询方法 hql-->hibernate public List executeQuery(String hql,Object[] parameters); //3.查询方法 带分页 public List executeQueryByPage(String hql,Object[] parameters,int pageNow,int pageSize); //4.添加一个对象 public void add(Object obj); //5.统一的执行hql->删除、修改 hql="update domain对象 where ?" public List executeUpdate(String hql,Object[] parameters); }定义一个实现基础接口的抽象类:
package com.cdtax.basic; import java.io.Serializable; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.transaction.annotation.Transactional; @Transactional public abstract class BasicService implements BasicServiceInter { @Resource private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Object findById(Class clazz, Serializable id) { return this.sessionFactory.getCurrentSession().get(clazz, id); } //统一的查询方法(hql) public List executeQuery(String hql, Object[] parameters) { Query query = this.sessionFactory.getCurrentSession().createQuery(hql); //注入?值 if(parameters != null && parameters.length > 0) { for(int i = 0; i < parameters.length; i++) { query.setParameter(i, parameters[i]); } } return query.list(); } //分页 public List executeQueryByPage(String hql, Object[] parameters, int pageNow, int pageSize) { Query query = this.sessionFactory.getCurrentSession().createQuery(hql); if(parameters != null && parameters.length > 0) { for(int i = 0; i < parameters.length; i++) { query.setParameter(i, parameters[i]); } } return query.setFirstResult((pageNow-1)*pageSize).setMaxResults(pageSize).list(); } public void add(Object obj) { this.sessionFactory.getCurrentSession().save(obj); } public List executeUpdate(String hql, Object[] parameters) { // TODO Auto-generated method stub return null; } }修改业务service接口,使其继承BasicServiceInter接口:
package com.cdtax.service.interfaces; import com.cdtax.basic.BasicServiceInter; import com.cdtax.domain.Department; public interface DepartmentServiceInter extends BasicServiceInter { //1.如果有比较特殊的方法,可以在这里定义 }
package com.cdtax.service.interfaces; import java.util.List; import com.cdtax.basic.BasicServiceInter; import com.cdtax.domain.Employee; public interface EmployeeServiceInter extends BasicServiceInter { //如果该雇员存在,则返回该雇员的完整信息,否则返回null public Employee checkEmployee(Employee e); }可以看出,业务接口极大简化了。
修改业务实现类,其继承抽象类BasicService并实现相应的业务接口
package com.cdtax.service.impl; import java.io.Serializable; import java.util.List; import javax.annotation.Resource; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.transaction.annotation.Transactional; import com.cdtax.basic.BasicService; import com.cdtax.domain.Department; import com.cdtax.domain.Employee; import com.cdtax.service.interfaces.EmployeeServiceInter; //这里配置@Tansactional用处是让spring的事务管理器接管该service的事务 //如果只想让事务管理器管理某个方法中的事务,那么就将注解加到方法上 public class EmployeeService extends BasicService implements EmployeeServiceInter { //验证用户 public Employee checkEmployee(Employee e) { String hql="from Employee where id=? and pwd=?"; Object[] parameters = {e.getId(),e.getPwd()}; List list = this.executeQuery(hql, parameters); if(list.size() == 0) { return null; } else { return (Employee)list.get(0); } } }
package com.cdtax.service.impl; import java.io.Serializable; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.transaction.annotation.Transactional; import com.cdtax.basic.BasicService; import com.cdtax.domain.Department; import com.cdtax.service.interfaces.DepartmentServiceInter; @Transactional public class DepartmentService extends BasicService implements DepartmentServiceInter { }
package com.cdtax.web.action; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import com.cdtax.domain.Department; import com.cdtax.domain.Employee; import com.cdtax.service.interfaces.DepartmentServiceInter; import com.cdtax.service.interfaces.EmployeeServiceInter; import com.cdtax.web.forms.EmployeeForm; public class EmployeeAction extends DispatchAction { @Resource private DepartmentServiceInter departmentService; @Resource private EmployeeServiceInter employeeService; public void setDepartmentService(DepartmentServiceInter departmentService) { this.departmentService = departmentService; } public void setEmployeeService(EmployeeServiceInter employeeService) { this.employeeService = employeeService; } public ActionForward addEmpUi(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //打通流程 return mapping.findForward("goAddEmp"); } //处理添加雇员的请求 public ActionForward addEmp(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //看看这里是否能够得到用户提交的各种数据 EmployeeForm employeeForm = (EmployeeForm)form; // System.out.println(employeeForm.getDepartmentId() + " |" + // employeeForm.getEmail() + " |" + employeeForm.getGrade() // + " |" + employeeForm.getName() + " |" + employeeForm.getPwd() // + " |" + employeeForm.getSalary()); //创建一个Employee对象,DAO Employee employee = new Employee(); employee.setEmail(employeeForm.getEmail()); employee.setGrade(Integer.parseInt(employeeForm.getGrade())); employee.setHiredate(new java.util.Date()); employee.setName(employeeForm.getName()); employee.setPwd(employeeForm.getPwd()); employee.setSalary(Float.parseFloat(employeeForm.getSalary())); //该雇员是哪个部门的 employee.setDepartment((Department)departmentService.findById(Department.class, Integer.parseInt(employeeForm.getDepartmentId()))); //保存雇员 try { employeeService.add(employee); } catch (Exception e) { return mapping.findForward("opererr"); } return mapping.findForward("operok"); } }
下一步做雇员信息的显示,从mainframe.jsp发出请求。
<body> <h2>欢迎 ${loginer.name} 所在部门: ${loginer.department.name}请选择你要的操作</h2> <a href="${pageContext.request.contextPath}/employee.do?flag=addEmpUi">添加雇员</a> <a href="${pageContext.request.contextPath}/employee.do?flag=goListEmp">显示雇员</a> <a href="#">修改雇员</a> <a href="#">退出系统</a> </body>修改EmployeeAction:
增加如下方法
public ActionForward goListEmp(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //打通流程 return mapping.findForward("goListEmp"); }
<!-- 配置employeeAction --> <action path="/employee" name="employeeForm" parameter="flag"> <forward name="goAddEmp" path="/WEB-INF/addemp.jsp" /> <forward name="goListEmp" path="/WEB-INF/listEmp.jsp"></forward> </action>
<%@ 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>My JSP 'listEmp.jsp' starting page</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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>雇员信息</h1> </body> </html>这是打通流程。
然后修改EmployeeServiceInter和EmployeeService,增加一个查询所有雇员的方法:
package com.cdtax.service.interfaces; import java.util.List; import com.cdtax.basic.BasicServiceInter; import com.cdtax.domain.Employee; public interface EmployeeServiceInter extends BasicServiceInter { //显示所有雇员 public List showEmployeeList(); //如果该雇员存在,则返回该雇员的完整信息,否则返回null public Employee checkEmployee(Employee e); }
package com.cdtax.service.impl; import java.io.Serializable; import java.util.List; import javax.annotation.Resource; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.transaction.annotation.Transactional; import com.cdtax.basic.BasicService; import com.cdtax.domain.Department; import com.cdtax.domain.Employee; import com.cdtax.service.interfaces.EmployeeServiceInter; //这里配置@Tansactional用处是让spring的事务管理器接管该service的事务 //如果只想让事务管理器管理某个方法中的事务,那么就将注解加到方法上 public class EmployeeService extends BasicService implements EmployeeServiceInter { //显示所有雇员 public List showEmployeeList() { String hql = "from Employee"; return this.executeQuery(hql, null); } //验证用户 public Employee checkEmployee(Employee e) { String hql="from Employee where id=? and pwd=?"; Object[] parameters = {e.getId(),e.getPwd()}; List list = this.executeQuery(hql, parameters); if(list.size() == 0) { return null; } else { return (Employee)list.get(0); } } }
修改EmployeeAction的goListEmp方法:
public ActionForward goListEmp(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //将查询的结果保存到request中返回到前台页面 request.setAttribute("emplist", employeeService.showEmployeeList()); //打通流程 return mapping.findForward("goListEmp"); }
request.setAttribute("emplist", employeeService.executeQuery("from Employee", null));就不需要修改上面的EmployeeServiceInter和EmployeeService,之所以这样做,是为了分层的明晰性,Action中不处理业务逻辑。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% 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>My JSP 'listEmp.jsp' starting page</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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>雇员信息</h1> <table> <tr><td>id</td><td>name</td><td>email</td><td>grade</td><td>salary</td><td>修改</td><td>删除</td></tr> <c:forEach items="${emplist }" var="emp"> <tr><td>${emp.id }</td><td>${emp.name }</td> <td>${emp.email }</td><td>${emp.grade }</td> <td>${emp.salary }</td><td><a href="">修改用户</a></td> <td><a href="">删除用户</a></td></tr> </c:forEach> </table> </body> </html>下面考虑分页:
在基础接口中增加方法:
package com.cdtax.basic; import java.util.List; public interface BasicServiceInter { //声明一些常用的方法 //1.通过id获取对象 public Object findById(Class clazz,java.io.Serializable id); //2.查询方法 hql-->hibernate public List executeQuery(String hql,Object[] parameters); //3.查询方法 带分页 public List executeQueryByPage(String hql,Object[] parameters,int pageNow,int pageSize); //4.添加一个对象 public void add(Object obj); //5.统一的执行hql->删除、修改 hql="update domain对象 where ?" public List executeUpdate(String hql,Object[] parameters); //6、返回一个对象的操作 public Object uniqueQuery(String hql,Object[] parameters); //7、得到hql,返回pageCount public int queryPageCount(String hql,Object[] parameters,int pageSize); }修改基础抽象类
package com.cdtax.basic; import java.io.Serializable; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.transaction.annotation.Transactional; @Transactional public abstract class BasicService implements BasicServiceInter { @Resource private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Object findById(Class clazz, Serializable id) { return this.sessionFactory.getCurrentSession().get(clazz, id); } //统一的查询方法(hql) public List executeQuery(String hql, Object[] parameters) { Query query = this.sessionFactory.getCurrentSession().createQuery(hql); //注入?值 if(parameters != null && parameters.length > 0) { for(int i = 0; i < parameters.length; i++) { query.setParameter(i, parameters[i]); } } return query.list(); } //分页 public List executeQueryByPage(String hql, Object[] parameters, int pageNow, int pageSize) { Query query = this.sessionFactory.getCurrentSession().createQuery(hql); if(parameters != null && parameters.length > 0) { for(int i = 0; i < parameters.length; i++) { query.setParameter(i, parameters[i]); } } return query.setFirstResult((pageNow-1)*pageSize).setMaxResults(pageSize).list(); } public void add(Object obj) { this.sessionFactory.getCurrentSession().save(obj); } public List executeUpdate(String hql, Object[] parameters) { // TODO Auto-generated method stub return null; } public Object uniqueQuery(String hql, Object[] parameters) { Query query = this.sessionFactory.getCurrentSession().createQuery(hql); //给?赋值 if(parameters != null && parameters.length > 0) { for(int i = 0;i < parameters.length;i++) { query.setParameter(i, parameters[i]); } } return query.uniqueResult(); } public int queryPageCount(String hql, Object[] parameters, int pageSize) { Object obj = this.uniqueQuery(hql, parameters); int rowCount = Integer.parseInt(obj.toString()); return (rowCount-1)/pageSize + 1; } }修改EmployeeServiceInter
package com.cdtax.service.interfaces; import java.util.List; import com.cdtax.basic.BasicServiceInter; import com.cdtax.domain.Employee; public interface EmployeeServiceInter extends BasicServiceInter { //显示所有雇员 public List showEmployeeList(int pageSize,int pageNow); //如果该雇员存在,则返回该雇员的完整信息,否则返回null public Employee checkEmployee(Employee e); public int getPageCount(int pageSize); }修改EmployeeService
package com.cdtax.service.impl; import java.io.Serializable; import java.util.List; import javax.annotation.Resource; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.transaction.annotation.Transactional; import com.cdtax.basic.BasicService; import com.cdtax.domain.Department; import com.cdtax.domain.Employee; import com.cdtax.service.interfaces.EmployeeServiceInter; //这里配置@Tansactional用处是让spring的事务管理器接管该service的事务 //如果只想让事务管理器管理某个方法中的事务,那么就将注解加到方法上 public class EmployeeService extends BasicService implements EmployeeServiceInter { //显示所有雇员 public List showEmployeeList(int pageSize,int pageNow) { String hql = "from Employee order by id"; return this.executeQueryByPage(hql, null, pageNow, pageSize); } public int getPageCount(int pageSize) { String hql = "Select count(*) from Employee"; return this.queryPageCount(hql, null, pageSize); } //验证用户 public Employee checkEmployee(Employee e) { String hql="from Employee where id=? and pwd=?"; Object[] parameters = {e.getId(),e.getPwd()}; List list = this.executeQuery(hql, parameters); if(list.size() == 0) { return null; } else { return (Employee)list.get(0); } } }
public ActionForward goListEmp(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String s_pageNow = request.getParameter("pageNow"); int pageNow = 1; if(s_pageNow != null) { pageNow = Integer.parseInt(s_pageNow); } //将查询的结果保存到request中返回到前台页面 request.setAttribute("emplist", employeeService.showEmployeeList(3,pageNow)); int pageCount = employeeService.getPageCount(3); request.setAttribute("pageCount", pageCount); //打通流程 return mapping.findForward("goListEmp"); }修改显示:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% 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>My JSP 'listEmp.jsp' starting page</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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>雇员信息</h1> <table> <tr><td>id</td><td>name</td><td>email</td><td>grade</td><td>salary</td><td>修改</td><td>删除</td></tr> <c:forEach items="${emplist }" var="emp"> <tr><td>${emp.id }</td><td>${emp.name }</td> <td>${emp.email }</td><td>${emp.grade }</td> <td>${emp.salary }</td><td><a href="">修改用户</a></td> <td><a href="">删除用户</a></td></tr> </c:forEach> </table> <c:forEach var="i" begin="1" end="${pageCount }"> <a href="${pageContext.request.contextPath}/employee.do?flag=goListEmp&pageNow=${i }">${i }</a> </c:forEach> </body> </html>
listEmp.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% 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>My JSP 'listEmp.jsp' starting page</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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript" language="javascript" src="/myssh/js/jquery-1.8.0.js"></script> <script type="text/javascript" language="javascript" src="/myssh/js/my.js"></script> </head> <body> <h1>雇员信息</h1> <table> <tr><td>id</td><td>name</td><td>email</td><td>grade</td><td>salary</td><td>修改</td><td>删除</td></tr> <c:forEach items="${emplist }" var="emp"> <tr><td>${emp.id }</td><td>${emp.name }</td> <td>${emp.email }</td><td>${emp.grade }</td> <td>${emp.salary }</td><td><a href="">修改用户</a></td> <td><a class="delid" href="${pageContext.request.contextPath}/employee.do?flag=delEmp&id=${emp.id }">删除用户</a></td></tr> </c:forEach> </table> <c:forEach var="i" begin="1" end="${pageCount }"> <a href="${pageContext.request.contextPath}/employee.do?flag=goListEmp&pageNow=${i }">${i }</a> </c:forEach> </body> </html>这里引入了jquery,在删除的时候弹出一个提示框,询问是否确认删除。
my.js
$(document).ready(function(){ $(".delid").click(function(){ window.confirm("你确定删除吗?"); }); });修改EmployeeAction,增加delEmp方法
public ActionForward delEmp(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //获取雇员id String id = request.getParameter("id"); System.out.println("删除id=" + id); try { employeeService.delById(Employee.class,Integer.parseInt(id)); } catch(Exception e) { return mapping.findForward("opererr"); } //打通流程 return mapping.findForward("operok"); }
package com.cdtax.basic; import java.util.List; public interface BasicServiceInter { //声明一些常用的方法 //1.通过id获取对象 public Object findById(Class clazz,java.io.Serializable id); //2.查询方法 hql-->hibernate public List executeQuery(String hql,Object[] parameters); //3.查询方法 带分页 public List executeQueryByPage(String hql,Object[] parameters,int pageNow,int pageSize); //4.添加一个对象 public void add(Object obj); //5.统一的执行hql->删除、修改 hql="update domain对象 where ?" public List executeUpdate(String hql,Object[] parameters); //6、返回一个对象的操作 public Object uniqueQuery(String hql,Object[] parameters); //7、得到hql,返回pageCount public int queryPageCount(String hql,Object[] parameters,int pageSize); //8、根据id号删除对象 public void delById(Class clazz,java.io.Serializable id); }
public void delById(Class clazz,Serializable id) { Session session = this.sessionFactory.getCurrentSession(); session.delete(this.findById(clazz, id)); }
<body> <h1>恭喜你,操作成功</h1> <br> <a href="#">返回继续添加</a><br/> <a href="${pageContext.request.contextPath}/login.do?flag=goMainFrame">返回主界面</a> <!-- 注意/WEB-INF文件夹是不能通过浏览器直接访问的 <a href="/WEB-INF/mainFrame.jsp">返回主界面</a> --> </body>
public ActionForward goMainFrame(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if(request.getSession().getAttribute("loginer") != null) { return mapping.findForward("ok"); } return mapping.findForward("err"); }
修改listEmp.jsp
<body> <h1>雇员信息</h1> <table> <tr><td>id</td><td>name</td><td>email</td><td>grade</td><td>salary</td><td>修改</td><td>删除</td></tr> <c:forEach items="${emplist }" var="emp"> <tr><td>${emp.id }</td><td>${emp.name }</td> <td>${emp.email }</td><td>${emp.grade }</td> <td>${emp.salary }</td><td><a href="${pageContext.request.contextPath}/employee.do?flag=goUdEmpUi&id=${emp.id }">修改用户</a></td> <td><a class="delid" href="${pageContext.request.contextPath}/employee.do?flag=delEmp&id=${emp.id }">删除用户</a></td></tr> </c:forEach> </table> <c:forEach var="i" begin="1" end="${pageCount }"> <a href="${pageContext.request.contextPath}/employee.do?flag=goListEmp&pageNow=${i }">${i }</a> </c:forEach> </body>
在EmployeeAction中增加方法goUdEmpUi
public ActionForward goUdEmpUi(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //获取雇员id String id = request.getParameter("id"); //获取雇员 Employee e = (Employee) employeeService.findById(Employee.class, Integer.parseInt(id)); //显示雇员信息,在下一个页面显示 request.setAttribute("emp", e); return mapping.findForward("goUpdEmpUi"); }updEmpUi.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>My JSP 'updEmpUi.jsp' starting page</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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="${pageContext.request.contextPath}/employee.do?flag=updEmp" method="post"> <table> <tr><td>id</td><td><input type="text" name="id" readonly="readonly" value="${emp.id }" /></td></tr> <tr><td>name</td><td><input type="text" name="name" value="${emp.name }" /></td></tr> <tr><td>email</td><td><input type="text" name="email" value="${emp.email }" /></td></tr> <tr><td>grade</td><td><input type="text" name="grade" value="${emp.grade }" /></td></tr> <tr><td>pwd</td><td><input type="text" name="pwd" value="${emp.pwd }"/></td></tr> <tr><td>salary</td><td><input type="text" name="salary" value="${emp.salary }"/></td></tr> <tr><td>department</td> <td> <!-- 这里的部门信息,应该从数据库提取,而不应该写死 --> <select name="departmentId"> <option value="1">财务部</option> </select> </td> </tr> <tr><td><input type="submit" value="修改" /></td> <td><input type="reset" value="重置" /></td></tr> </table> </form> </body> </html>id不能修改,使用readonly属性
提交修改的方法,在EmployeeAction中增加方法updEmp,对修改信息进行提交
public ActionForward updEmp(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //获取表单 EmployeeForm ef = (EmployeeForm)form; //ef->domain Employee employee = new Employee(); employee.setId(Integer.parseInt(ef.getId())); employee.setEmail(ef.getEmail()); employee.setGrade(Integer.parseInt(ef.getGrade())); employee.setPwd(ef.getPwd()); employee.setName(ef.getName()); employee.setSalary(Float.parseFloat(ef.getSalary())); employee.setDepartment((Department)departmentService.findById(Department.class,Integer.parseInt(ef.getDepartmentId()))); try { employeeService.update(employee); } catch(Exception e) { return mapping.findForward("opererr"); } return mapping.findForward("operok"); }
<action path="/employee" name="employeeForm" parameter="flag"> <forward name="goAddEmp" path="/WEB-INF/addemp.jsp" /> <forward name="goListEmp" path="/WEB-INF/listEmp.jsp"></forward> <forward name="goUpdEmpUi" path="/WEB-INF/updEmpUi.jsp"></forward> </action>基础接口中增加方法
//9、通过object修改 public void update(Object obj);基础抽象实现类
public void update(Object obj) { this.sessionFactory.getCurrentSession().update(obj); }