本章教程来讲新建一个子菜单模块的增删改查功能。
一:新建javabean,维修人员
在model_src包下创建包repairman,新建类和hbm配置文件
TbRepairMan.java
package com.djzhou.gmms.model.repairman; import java.util.Date; import com.djzhou.gmms.model.entity.Entity; import com.djzhou.gmms.model.entity.EntitySerializable; /** * 维修人员信息表 * @author wolf * */ @SuppressWarnings("serial") public class TbRepairMan extends Entity implements EntitySerializable<TbRepairMan>, Cloneable { private Integer repairManId;//ID private String loginName;//登录名手机号 private String realName;//真名 private String password;//密码 private String address;//地址 private Integer deleteFlag;//删除标识 private String phone;//联系电话 private Integer busy;//是否在进行任务中,1为正在进行任务,其他为空闲 private Date createTime;//最后操作时间 public Object clone() throws CloneNotSupportedException { TbRepairMan cloned = (TbRepairMan) super.clone(); cloned.createTime = (Date) createTime.clone(); return cloned; } @Override public TbRepairMan toAjaxObject() { try { return (TbRepairMan) this.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } public Integer getBusy() { return busy; } public void setBusy(Integer busy) { this.busy = busy; } public Integer getRepairManId() { return repairManId; } public void setRepairManId(Integer repairManId) { this.repairManId = repairManId; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getDeleteFlag() { return deleteFlag; } public void setDeleteFlag(Integer deleteFlag) { this.deleteFlag = deleteFlag; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
<span style="font-size:12px;"><?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="com.djzhou.gmms.model.repairman.TbRepairMan" table="tb_repair_man"> <id name="repairManId"> <generator class="native"> </generator> </id> <property name="loginName" not-null="true" unique="true"/> <property name="password" not-null="true"/> <property name="realName" /> <property name="address" /> <property name="deleteFlag" /> <property name="phone" /> <property name="busy" /> <property name="createTime" /> </class> </hibernate-mapping> </span>
设置了一下不能为空,不能重复的属性。这样javabean就建好了。
直接继承Base类即可,比较简单
RepairManDAO.java
package com.djzhou.gmms.dao.repairman; import com.djzhou.gmms.dao.base.BaseDAO; import com.djzhou.gmms.model.repairman.TbRepairMan; public interface RepairManDAO extends BaseDAO<TbRepairMan>{ }
RepairManDAOImpl.java
package com.djzhou.gmms.dao.repairman.impl; import com.djzhou.gmms.dao.base.impl.BaseDAOImpl; import com.djzhou.gmms.dao.repairman.RepairManDAO; import com.djzhou.gmms.model.repairman.TbRepairMan; public class RepairManDAOImpl extends BaseDAOImpl<TbRepairMan> implements RepairManDAO{ }
RepairManService.java 也是直接继承就好
package com.djzhou.gmms.service.repairman; import com.djzhou.gmms.model.repairman.TbRepairMan; import com.djzhou.gmms.service.base.BaseService; public interface RepairManService extends BaseService<TbRepairMan>{ }RepairManServiceImpl.java 这个类需要根据自己的业务来写代码,里面有分页相关的需要注意
package com.djzhou.gmms.service.repairman.impl; import java.util.HashMap; import java.util.List; import com.djzhou.gmms.model.entity.PageBean; import com.djzhou.gmms.model.repairman.TbRepairMan; import com.djzhou.gmms.model.user.VoResource; import com.djzhou.gmms.service.base.impl.BaseServiceImpl; import com.djzhou.gmms.service.repairman.RepairManService; import jodd.util.StringUtil; public class RepairManServiceImpl extends BaseServiceImpl implements RepairManService { @Override public void add(TbRepairMan t) { repairManDAO.insert(t); } @Override public void update(TbRepairMan t) { repairManDAO.update(t); } @Override public void delete(Integer id) { TbRepairMan repairMan = repairManDAO.queryByID(TbRepairMan.class, id); repairMan.setDeleteFlag(1); repairManDAO.update(repairMan); } @Override public PageBean<TbRepairMan> queryPageBean(HashMap<String, Object> hashMap, int pageSize, int currentPage, String orderColumn, String orderWay) { String hql = "from TbRepairMan where deleteFlag=0 "; StringBuffer sb = new StringBuffer(); sb.append(hql); if (StringUtil.isNotEmpty(orderColumn) && StringUtil.isNotEmpty(orderWay)) { sb.append(" order by ").append(orderColumn).append(" ").append(orderWay); } else { sb.append(" order by createTime desc"); } hql = sb.toString(); PageBean<TbRepairMan> pageBean = repairManDAO.selectByPage(hql, pageSize, currentPage); return pageBean; } @Override public List<TbRepairMan> queryList(HashMap<String, Object> hashMap) { // 查询所有不忙的集合 String hql = "from TbRepairMan repairman where repairman.deleteFlag=0 "; return repairManDAO.query(hql); } @Override public TbRepairMan queryById(Integer id) { return repairManDAO.queryByID(TbRepairMan.class, id); } @Override public VoResource query4AutoComplete(HashMap<String, Object> hashMap, String sidx, String sord, int pageSize, int currentPage) { // TODO Auto-generated method stub return null; } }需要在BaseServiceImpl里添加repairManDAO的定义和set、get方法。
这个serviceImpl里面主要到分页做了一些处理,其他的都是基本的增删改查,比较简单。
创建完以上三个后,system层的就算完成了,后续在页面和action层如果有什么业务的需求,就回来修改service接口和实现类,来完成特定的业务。
下面来说web层的修改。
四:配置xml文件
打开config文件夹,修改dao和service的xml配置,新增上自己的配置。
dao.xml里加一句 <bean id="repairManDAO" class="com.djzhou.gmms.dao.repairman.impl.RepairManDAOImpl" parent="baseDAO" />
service.xml里加上<property name="repairManDAO" ref="repairManDAO" />
<bean id="repairManService" class="com.djzhou.gmms.service.repairman.impl.RepairManServiceImpl" parent="baseService" />
这两项就OK。
然后在hibernate.cfg.xml里把model里定义的xml引进来<mapping resource="com/djzhou/gmms/model/repairman/TbRepairMan.hbm.xml" />
然后就配置好了各项注入了。重新启动项目时,数据库表就能建出来了。
五:Action创建
创建一个action类,先来做一个查询并展示的功能
package com.djzhou.gmms.repairman.action; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import com.djzhou.gmms.base.action.BaseAction; import com.djzhou.gmms.model.repairman.TbRepairMan; import com.djzhou.util.StaticUtil; import jodd.util.StringUtil; @SuppressWarnings("serial") public class RepairManAction extends BaseAction<TbRepairMan> { private TbRepairMan repairMan; private Integer repairManId; private List<TbRepairMan> list; @Override public String queryList() { if (loadData == null) return SUCCESS; HashMap<String, Object> hashMap = new HashMap<String, Object>(); pageBean = repairManService.queryPageBean(hashMap, pageSize, currentPage, orderColumn, orderWay); list = pageBean.getList(); if (currentPage > 1) { if (list == null || list.size() == 0) { setCurrentPage(getCurrentPage() - 1); pageBean = repairManService.queryPageBean(hashMap, pageSize, currentPage, orderColumn, orderWay); list = pageBean.getList(); } } if (list != null) { totalCount = pageBean.getAllRow(); } else { totalCount = 0; list = new ArrayList<TbRepairMan>(); } totalPage = pageBean.getTotalPage(); return SUCCESS; } @Override public String delete() { repairManService.delete(repairManId); msg = "数据删除成功"; logService.addLog("RepairMan", queryUser(), StaticUtil.LOG_DELETE, repairManId, queryCompany(), getLogValue()); return SUCCESS; } @Override public String modify() { repairMan.setCreateTime(new Date()); repairManService.update(repairMan); msg = "数据保存成功"; logService.addLog("RepairMan", queryUser(), StaticUtil.LOG_EDIT, repairMan.getRepairManId(), queryCompany(), getLogValue()); return SUCCESS; } @Override public String save() { if (repairMan != null) { repairMan.setCreateTime(new Date()); repairMan.setDeleteFlag(0); repairManService.add(repairMan); msg = "数据保存成功"; logService.addLog("RepairMan", queryUser(), StaticUtil.LOG_ADD, repairMan.getRepairManId(), queryCompany(), getLogValue()); } return SUCCESS; } @Override public String toEdit() { repairMan = repairManService.queryById(repairManId); return SUCCESS; } public String query4AutoComplete() { HashMap<String, Object> hashMap = new HashMap<String, Object>(); if (StringUtil.isNotEmpty(searchStr)) hashMap.put("searchStr", searchStr); if (StringUtil.isNotEmpty(repairManId + "")) hashMap.put("streetId", repairManId); resource = repairManService.query4AutoComplete(hashMap, sidx, sord, rows, page); return SUCCESS; } public TbRepairMan getRepairMan() { return repairMan; } public void setRepairMan(TbRepairMan repairMan) { this.repairMan = repairMan; } public Integer getRepairManId() { return repairManId; } public void setRepairManId(Integer repairManId) { this.repairManId = repairManId; } public List<TbRepairMan> getList() { return list; } public void setList(List<TbRepairMan> list) { this.list = list; } }
action写好后需要在BaseAction里把自己的service给写进去 设置set、get方法,供action使用
struts-repairman.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="repairManPackage" namespace="/repairMan" extends="json-default"> <interceptors> <interceptor name="sessionInterceptor" class="com.djzhou.gmms.util.interceptor.SessionInterceptor"/> <interceptor-stack name="defaultStack"> <interceptor-ref name="defaultStack"/> <interceptor-ref name="sessionInterceptor"/> </interceptor-stack> </interceptors> <default-interceptor-ref name="defaultStack" /> <action name="repairMan_*_*Action" class="com.djzhou.gmms.repairman.action.RepairManAction" method="{1}"> <result name="success">/WEB-INF/pages/repairman/{2}.jsp</result> </action> <action name="repairManAjax_*_*Action" class="com.djzhou.gmms.repairman.action.RepairManAction" method="{1}"> <result name="success" type="json"> <param name="root">{2}</param> </result> </action> </package> </struts>
稍微解释一下这个struts配置文件,package name是包名,区分于其他包,同一个包下的享有共同的约束,这里就每个模块一个包名,namespace比较重要,代表浏览器访问时需要敲的字,后面用到时会提到。interceptors是拦截器,通过com.djzhou.gmms.util.interceptor.SessionInterceptor这个拦截器来对所有的请求进行拦截,主要是防止用户未登录时直接访问action用的。action name里面的*是通配符,第一个*对应后面的{1},第二个*对应{2}。像这个action意思就是,如果你访问repaiMan_queryList_listAction,那么系统就会调用RepairManAction类的queryList方法,如果返回了success,就会跳到/WEB-INF/pages/repairman/list.jsp这个页面。
这个action里有几个方法是override的,因为照抄这个框架的一些页面的话,里面会自动调用对应的方法名,这是一种约束,方便开发。
action里的代码也是从别的action照抄的,照抄后就具备分页功能了,非常方便。
六:创建jsp页面
在web-inf,pages,新建自己的文件夹repairman,注意和struts里的配置相同。
然后创建list.jsp这个名字是固定的
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <%@ taglib prefix="s" uri="/struts-tags"%> <%@ taglib prefix="gmms" uri="/gmms-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <c:choose> <c:when test="${loadData==null}"> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>维修人员管理</title> <jsp:include page="../head.jsp" /> <script language="javascript"> function del(keyId){ xbox.confirm("您正在执行删除操作,确认吗?", function (result) { if (result) { $.ajax({ url :"<%=path%>/repairMan/repairManAjax_delete_msgAction.action", type : "POST", dataType : "json", data : { "repairManId" : keyId }, success : function(data) { j_loadData($("#currentPage").val()); }, error :function(){ xbox.alert("数据正在提交,请稍候,或检查您的网络环境,确保其连接正常!"); } }); } }, { title: '系统提示', value: '确定' }); } function toAdd(){ j_goUrl("<%=path%>/repairMan/repairMan_toAdd_addAction.action",1); } function toEdit(keyId){ j_goUrl("<%=path%>/repairMan/repairMan_toEdit_editAction.action?repairManId="+keyId,$("#currentPage").val()); } function toConfig(keyId){ $.ajax({ url :"<%=path%>/repairMan/repairManAjax_toConfig_msgAction.action", type : "POST", dataType : "json", data : { "keyId" : keyId }, success : function(data) { j_loadData($("#currentPage").val()); }, error :function(){ xbox.alert("数据正在提交,请稍候,或检查您的网络环境,确保其连接正常!"); } }); } </script> </head> <body> <div class="info_right_main"> <form action="<%=path%>/repairMan/repairMan_queryList_listAction.action" method="post" id="refreshForm" name="refreshForm"> <input type="hidden" id="currentPage" name="currentPage" value="${currentPage}"/> <input type="hidden" id="orderColumn" name="orderColumn" value="${orderColumn}"/> <input type="hidden" id="orderWay" name="orderWay" value="${orderWay}"/> </form> <div class="info_right_ctrl"> <input class="btn btn-default" onclick="toAdd();" type="button" value='${menuTagMap["add_repair_man"]}' /> <input class="btn btn-default" type="button" onclick="j_search(1,true);" value='${totalTagMap["btnRefresh"]}' /> <span style="font-size:13px;padding-top:15px;float:right;padding-right:30p帮助rsor帮助inter;" onclick="operationManual(${currentMenuId})"> <img src="<%=path %>/images/help.png" title='${totalTagMap["btnHelp"]}' />${totalTagMap["btnHelp"]} </span> </div> <div class="info_right_main"> <div id="gridHead"> <table width="100%" border="0" cellspacing="0" cellpadding="0" style="TABLE-LAYOUT:fixed;"> <tr height="35"> <td width="60" align="center"><strong>${totalTagMap["serialNumber"]}</strong></td> <td width="100" align="center" orderColumn="repairManId"><strong>维修人员ID</strong></td> <td width="100" align="center" orderColumn="loginName"><strong>登录名</strong></td> <td width="100" align="center" orderColumn="realName"><strong>真实姓名</strong></td> <td width="200" align="center" orderColumn="address"><strong>地址</strong></td> <td width="100" align="center" orderColumn="busy"><strong>进行任务中</strong></td> <td width="150" align="center" orderColumn="createTime"><strong>最后编辑时间</strong></td> <td width="50" align="center"><strong>操作</strong></td> </tr> </table> </div> <div style="overflow:auto;display:none;" id="divGrid"> </div> <table border="0" cellspacing="0" cellpadding="0" width="100%" id="tablePager"></table> </div> </div> </body> </html> </c:when> <c:otherwise> <table id="gridTable" width="100%" border="0" cellspacing="0" cellpadding="0"> <c:forEach items="${list}" var="repairMan" varStatus="status"> <tr align='center' bgcolor="#FFFFFF" onMouseMove="javascript:this.bgColor='#f1f1f1';" onMouseOut="javascript:this.bgColor='#FFFFFF';" height="30" > <td>${status.index+1+(currentPage-1)*pageSize}</td> <td>${repairMan.repairManId}</td> <td>${repairMan.loginName}</td> <td>${repairMan.realName}</td> <td>${repairMan.address}</td> <c:choose> <c:when test="${repairMan.busy eq 1}"><td>是</td></c:when> <c:otherwise><td>否</td></c:otherwise> </c:choose> <td><fmt:formatDate value="${repairMan.createTime}" pattern="yyyy-MM-dd HH:mm"/></td> <td> <c:if test='${fn:contains(authorityCode,",0001,") or fn:contains(authorityCode,",0003,")}'> <span style="width:140px;"><input class="btn btn-default" onclick="toEdit(${repairMan.repairManId});" type="button" value="编辑" /></span> </c:if> <c:if test='${fn:contains(authorityCode,",0001,") or fn:contains(authorityCode,",0004,")}'> <input class="btn btn-default" onclick="del(${repairMan.repairManId});" type="button" value="删除" /> </c:if> <%-- <c:if test='${fn:contains(authorityCode,",0001,") or fn:contains(authorityCode,",HISTORY,")}'> <span style="width:140px;"><input class="btn btn-default" onclick="openModelWindow('查看历史版本','<%=path%>/company/company_redirect_historyAction.action?keyId=${company.companyId}¤tMenuId=${currentMenuId}');" type="button" value="历史" /></span> </c:if> --%> </td> </tr> </c:forEach> <tr align="right" bgcolor="#f1f1f1"> <td height="30" colspan="9" align="right"> <!-- 分页 --> <gmms:pages currentPage="%{currentPage}" totalPage="%{totalPage}" /> </td> </tr> </table> </c:otherwise> </c:choose>
可以手工在数据库里添加几条数据,看看列表展示效果。
当然,直接看到的界面可能不是这样,像 添加按钮为空之类的。这里就需要来调一下。
我们先来看看company的list.jsp文件,发现里面在“添加按钮”还有各属性的名字,都是用${menuTagMap["公司ID"]}这种方式来显示的。那么就来看看这个menuTagMap
在BaseAction里定义的有protected Map<String, String> menuTagMap,在530多行有给menuTagMap赋值的地方。是根据currentMenuId来获取当前菜单的一些标签定义。
这样就明白了,把这些中文的属性也存到数据库里,根据对应的key去取这些值,将来就可以在不动代码的情况下,直接修改页面显示的文字。类似于${menuTagMap["公司ID"]}就是在company菜单时,取出这个菜单里存的key为“公司ID”的value值。那么这个值在哪里设置呢?
打开页面,在系统管理-标签管理里可以看到。
譬如在所属菜单里选择 公司管理,点查询,就能看到有很多标签。其中索引减就是key,使用值就是value,知道了这,我们就可以添加自己菜单的标签了。
所属菜单选择 维修人员管理,查询,是空的,点 添加,然后添加这个菜单你需要用的标签
添加完自己需要的一些标签后,保存,然后重新登录。就能看到修改后的效果了,jsp里面用标签的地方就会自动赋值为中文了。
刚才贴list.jsp代码时还没有创建这些标签,所以又修改了一下代码,重新运行后,这个模块的查询功能就算做好了。
编辑功能
在list.jsp里有编辑和删除的入口,删除比较简单,直接带着id删除就行了。说一下编辑功能。
edit.jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>main</title> <jsp:include page="../head.jsp" /> <script type="text/javascript"> function save(){$("#btnSave").attr("disabled","disabled"); if (!checkForm(document.getElementById("saveForm"))) { return; } xbox.load("loading"); $("#saveForm").jefLog().ajaxSubmit({ success: function(date){ $("#refreshForm").submit(); }, error:function(){ xbox.ready("loading"); xbox.alert("数据正在提交,请稍候,或检查您的网络环境,确保其连接正常!"); } }); } function turnBack(){ $("#refreshForm").submit(); } </script> </head> <body> <form action="<%=path%>/repairMan/repairManAjax_modify_listAction.action" method="post" id="saveForm"> <table width="98%" align="center" border="0" cellpadding="4" cellspacing="1" bgcolor="#F1F1F1" style="margin-bottom:8px"> <tr bgcolor="#FFFFFF"> <td colspan="4" height="16"><span></span></td> </tr> <tr bgcolor="#FFFFFF"> <td width="10%" align="right" bgcolor="#FFFFFF"><span style="color:red;">*</span>${menuTagMap["login_name"]}:</td> <td width="40%" align="left" bgcolor="#FFFFFF"> <input maxlength="100" type="text" name="repairMan.loginName" id="loginName" isNull='登录名' value="${repairMan.loginName}" /> </td> <td width="10%" align="right" bgcolor="#FFFFFF"><span style="color:red;">*</span>${menuTagMap["real_name"]}:</td> <td width="40%" align="left" bgcolor="#FFFFFF"> <input maxlength="100" type="text" name="repairMan.realName" isNull='${menuTagMap["real_name"]}' id="realName" value="${repairMan.realName}" /> </td> </tr> <tr bgcolor="#FFFFFF"> <td width="10%" align="right" bgcolor="#FFFFFF"><span style="color:red;">*</span>${menuTagMap["address"]}:</td> <td width="40%" align="left" bgcolor="#FFFFFF"> <input maxlength="100" type="text" name="repairMan.address" id="address" isNull='地址' value="${repairMan.address}" /> </td> <td width="10%" align="right" bgcolor="#FFFFFF"><span style="color:red;">*</span>${menuTagMap["busy"]}:</td> <td width="40%" align="left" bgcolor="#FFFFFF"> <input name="repairMan.busy" id="busy" type="radio" value="1" <c:if test="${repairMan.busy eq 1}">checked="checked"</c:if>/>繁忙 <input name="repairMan.busy" id="busy" type="radio" value="0" <c:if test="${repairMan.busy eq 0}">checked="checked"</c:if>/>空闲</td> </td> </tr> <tr align="right" bgcolor="#F1F1F1"> <td height="36" colspan="4" align="center"> <input type='button' class="btn btn-primary" id="btnSave" onclick="save();" value='保存' /> <input type='button' class="btn btn-default" onclick="turnBack();" value='返回' /> </td> </tr> </table> <input type="hidden" name="repairMan.repairManId" value="${repairMan.repairManId}"/> <input type="hidden" name="repairMan.password" value="${repairMan.password}"/> <input type="hidden" name="repairMan.deleteFlag" value="${repairMan.deleteFlag}"/> </form> <form action="${listUrl}" method="post" style="display: none;" id="refreshForm" name="refreshForm"/> </body> </html>
里面需要注意的地方注意在于下面的几个hidden属性,把那些不需要编辑的属性hidden起来,直接带到action里就行了。其他的没什么说的,比较简单。
删除功能只要action里写好就行了。在界面数据列表上右键,直接点删除就行了。这里就不多说。
添加功能也不多说了,和edit很像,只不过每个属性都需要列出来。参照别的模块的add.jsp抄一下就行。由于这个repairMan是app注册才能新建的,所有页面上就不留添加的入口了。