最近分配到了一个新的任务就是“数据字典”功能,改功能包括“字典分组管理”和“字典条目管理”其中的关系是 一对多关系。
用到的前端框架operamasks ui,mvc层是springmvc
下面是字典分组 效果图
下面是字典条目效果图
因为用到的是operamasks ui 所以在页面中的数据主要是通过ajax异步获取
下面是实现分组功能的 jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ 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" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <base href="<%= basePath %>"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>数据字典-类型管理</title> <link rel="stylesheet" type="text/css" href="resource/css/apusic/om-apusic.css" /> <script src="resource/js/json2.js"></script> <script src="resource/js/jquery.min.js"></script> <script src="resource/js/operamasks-ui.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#btn').omButtonbar({ //width : 600, btns : [ {label:"新增", id:"add" }, {label:"删除", id:"del" }, {label:"保存更改", id:"save" } ] }); $('#grid').omGrid({ limit:20, //width:600, //height : 700, colModel : [ {header : '分组名称', name : 'groupName', width : '120', align : 'left', editor:{ rules:["required",true,"请填写名称"], type:"text", editable:true, name:"groupName" }}, {header : '分组编码', name : 'groupCode', align : 'left', width : '120', editor:{ rules:[["required",true,"请填写编码"],['groupCode']], type:"text", editable:true, name:"groupCode" }}, {header:"ID",name:"id",editor:{editable:false}, width : 'autoExpand'}, ], dataSource : "admin/dic_groups/list", onBeforeEdit : function(){ $('#btn >:button').attr("disabled",true); }, onAfterEdit : function(){ $('btn >:button').removeAttr("disabled"); }, onCancelEdit : function(){ $('#btn >:button').removeAttr("disabled"); } }); $('#add').click(function(){ //需要在这里操作取消之前操作选择的行 $('#grid').omGrid('setSelections',-1); $('#grid').omGrid('insertRow',0,{id:'系统自动生成'}); }); $('#del').click(function(){ var dels = $('#grid').omGrid('getSelections'); if(dels.length <= 0 ){ $.omMessageBox.alert({ content:'请选择删除的记录!' }); return; } var id = $('#grid').omGrid('getSelections',true)[0].id; //alert(id); var dicObject = false; $.ajax({ type: "GET", url: "admin/dic_groups/existObject?id="+id, async: false, dataType: "json", success: function(data){ if(data.result=="success") dicObject =true; } }); if(!dicObject){ $.omMessageBox.alert({ content:'请先删除该分组下面的字典内容!' }); return; } $('#grid').omGrid('deleteRow',dels[0]); }); $('#save').click(function(){ var data = $('#grid').omGrid('getChanges'); //var formDataStr=eval(data); //alert(formDataStr); //alert(data.toString()); var formDataStr = JSON.stringify(data); //如果没有更改 则获取到的string为:{"update":[],"insert":[],"delete":[]} if('{"update":[],"insert":[],"delete":[]}'==formDataStr){ $.omMessageBox.alert({ content:'没有需要保存的内容!' }); return; } $.ajax({ type: "POST", url: "admin/dic_groups/save", data: {formData:formDataStr}, async: false, dataType: "json", success: function(data){ $.omMessageTip .show({ title : "操作成功", content : "保存成功", timeout : 1500 }); } }); $('#grid').omGrid('reload'); }); $.validator.addMethod("groupCode", function(value) { var dels = $('#grid').omGrid('getSelections'); var id=""; if(dels.length > 0 ){ id = $('#grid').omGrid('getSelections',true)[0].id; } var isOK = false; $.ajax({ type: "GET", url: "admin/dic_groups/exist?value="+value+"&id="+id, async: false, dataType: "json", success: function(data){ if(data.result=="success") isOK =true; } }); return isOK;}, '该编码已经存在'); }); </script> </head> <body> <div id="btn"></div> <table id="grid"></table> </body> </html>
下面是 字典条目 的jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ 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" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <base href="<%= basePath %>"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>数据字典-内容管理</title> <link rel="stylesheet" type="text/css" href="resource/css/apusic/om-apusic.css" /> <script src="resource/js/json2.js"></script> <script src="resource/js/jquery.min.js"></script> <script src="resource/js/operamasks-ui.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var genderOptions = { dataSource :"admin/dic_content/groupList", valueField : 'groupCode', optionField :function(data,index){ return "["+data.groupName+"]["+data.groupCode+"]"; }, editable: false }; $('#groupId').omCombo({ dataSource :"admin/dic_content/groupList", valueField : 'id', emptyText:'[分组名][分组编码]', optionField :function(data,index){ return "["+data.groupName+"]["+data.groupCode+"]"; }, onValueChange:function(target,newValue,oldValue,event){ $('#grid').omGrid("setData", 'admin/dic_content/list?groupId='+newValue); } }); $('#btn').omButtonbar({ //width : 600, btns : [ {label:"新增", id:"add" }, {label:"删除", id:"del" }, {label:"保存更改", id:"save" } ] }); $('#grid').omGrid({ limit:20, // width:600, // height : 600, colModel : [ {header : '字典名称(值)', name : 'name', width : 120, align : 'left', editor:{ rules:["required",true,"请填写名称"], type:"text", editable:true, name:"name" }}, {header : '值(键)', name : 'value', align : 'left', width : '120', editor:{ rules:[["required",true,"请填写值"],['values']], type:"text", editable:true, name:"value" }}, {header : '分组编码', name : 'groupCode', align : 'left', width : '120', rules:["required",true,"请选择分组"], editor:{ type:"omCombo", name:"groupCode" , options:genderOptions }}, {header : '优先级', name : 'priority', align : 'left', width : '120', editor:{ rules:[["required",true,"请填写编码"]], type:"omNumberField", editable:true, name:"priority" }}, {header:"ID",name:"id",editor:{editable:false}, width : 'autoExpand'} ], dataSource : "admin/dic_content/list", onBeforeEdit : function(){ $('#btn >:button').attr("disabled",true); }, onAfterEdit : function(){ $('btn >:button').removeAttr("disabled"); }, onCancelEdit : function(){ $('#btn >:button').removeAttr("disabled"); } }); $('#add').click(function(){ //需要在这里操作取消之前操作选择的行 //默认排序为1 $('#grid').omGrid('setSelections',-1); $('#grid').omGrid('insertRow',0,{id:'系统自动生成',priority:1}); }); $('#del').click(function(){ var dels = $('#grid').omGrid('getSelections'); if(dels.length <= 0 ){ $.omMessageBox.alert({ content:'请选择删除的记录!' }); return; } $('#grid').omGrid('deleteRow',dels[0]); }); $('#save').click(function(){ var data = $('#grid').omGrid('getChanges'); var formDataStr = JSON.stringify(data); //如果没有更改 则获取到的string为:{"update":[],"insert":[],"delete":[]} if('{"update":[],"insert":[],"delete":[]}'==formDataStr){ $.omMessageBox.alert({ content:'没有需要保存的内容!' }); return; } $.ajax({ type: "POST", url: "admin/dic_content/save", data: {formData:formDataStr}, async: false, dataType: "json", success: function(data){ $.omMessageTip .show({ title : "操作成功", content : "保存成功", timeout : 1500 }); } }); $('#grid').omGrid('reload'); }); $.validator.addMethod("values", function(value) { var dels = $('#grid').omGrid('getSelections'); var id=""; if(dels.length > 0 ){ id = $('#grid').omGrid('getSelections',true)[0].id; } var isOK = false; $.ajax({ type: "GET", url: "admin/dic_content/existName?value="+value+"&id="+id, async: false, dataType: "json", success: function(data){ if(data.result=="success") isOK =true; } }); return isOK;}, '该值已经存在'); }); </script> </head> <body> <input id="groupId" /> <div id="btn"></div> <table id="grid"></table> </body> </html>
处理 分组的 action
package org.shield.module.web.controller.admin.dictionary; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.map.ObjectMapper; import org.shield.commons.dictionary.IDictionaryGroupService; import org.shield.commons.dictionary.IDictionaryService; import org.shield.commons.entity.dictionary.DictionaryGroupsObject; import org.shield.omui.GridDataModel; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * 数据字段分组管理 * * @author hhy * */ @Controller @RequestMapping("/admin/dic_groups") public class DictionaryGroupsController { private static final String ERROR="error"; private static final String RESULT="result"; private static final String SUCCESS="success"; @Resource private IDictionaryGroupService dictionaryGroupService; @Resource private IDictionaryService dictionaryService; @RequestMapping(method = RequestMethod.GET) public String view(Model model) { DictionaryGroupsObject dicObject = new DictionaryGroupsObject(); model.addAttribute("dicObject", dicObject); return "/admin/dictionary/dic_groups"; } /** * 获取分页数据 * * @param request * @param response * @param model * @param limit * @param start * @return */ @SuppressWarnings("unused") @RequestMapping(value = "list", method = RequestMethod.GET) @ResponseBody private GridDataModel<DictionaryGroupsObject> dicGroupList( @RequestParam(required = false) GridDataModel<DictionaryGroupsObject> model, @RequestParam(required = false) int limit, @RequestParam(required = false) int start) throws Exception { if (model == null) { model = new GridDataModel<DictionaryGroupsObject>(); } List<DictionaryGroupsObject> list = new ArrayList<DictionaryGroupsObject>(); int total = (int) dictionaryGroupService.getTotalCount(); list = dictionaryGroupService.findPageByHQL(start, limit, "from DictionaryGroupsObject"); model.setTotal(total); model.setRows(list); return model; } /** * 处理数据字典的 增 删 改 * * @param request * @param response * @param formData * @return * @throws Exception */ @SuppressWarnings({ "unchecked" }) @RequestMapping(value = "save", method = RequestMethod.POST) @ResponseBody public Map<String, String> save( @RequestParam(required = false) String formData) throws Exception { Map<String, String> returnMap = new HashMap<String, String>(); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = (Map<String, Object>) mapper.readValue( formData, Map.class); // 处理添加 if (map.get("insert") != null && !(map.get("insert").toString()).equals("[]")) { List<DictionaryGroupsObject> dicList = getListFromJosn(map, "insert"); for (DictionaryGroupsObject dictionaryGroupsObject : dicList) { dictionaryGroupService.createOrModify(dictionaryGroupsObject); } returnMap.put(SUCCESS, "添加成功"); } //处理修改 if (map.get("update") != null && !(map.get("update").toString()).equals("[]")) { List<DictionaryGroupsObject> dicList = getListFromJosn(map, "update"); for (DictionaryGroupsObject dictionaryGroupsObject : dicList) { dictionaryGroupService.createOrModify(dictionaryGroupsObject); } returnMap.put(SUCCESS, "修改成功"); } //处理删除 if (map.get("delete") != null && !(map.get("delete").toString()).equals("[]")) { List<DictionaryGroupsObject> dicList = getListFromJosn(map, "delete"); for (DictionaryGroupsObject dictionaryGroupsObject : dicList) { dictionaryGroupService.removeById(dictionaryGroupsObject.getId()); } returnMap.put(SUCCESS, "删除成功"); } return returnMap; } /** * 校验编码是否存在 * @param request * @param response * @param value * @return * @throws Exception */ @RequestMapping(value = "exist", method = RequestMethod.GET) @ResponseBody public Map<String, String> exist( @RequestParam(required = false) String id, @RequestParam(required = false) String value)throws Exception { Map<String, String> returnMap = new HashMap<String, String>(); int count = 0; //校验添加 if(id.equals("")){ String hql ="select count(*) from DictionaryGroupsObject dic where dic.groupCode=?"; count =(int) dictionaryGroupService.getTotalCountByHQL(hql,new String[]{value}); if(count>0){ returnMap.put(RESULT, ERROR); }else{ returnMap.put(RESULT, SUCCESS); } return returnMap; } //校验修改 if (value != null && !value.equals("")) { String hql ="select count(*) from DictionaryGroupsObject dic where dic.groupCode=?"; count = (int) dictionaryGroupService.getTotalCountByHQL(hql,new String[]{value}); } if(count>1){ returnMap.put(RESULT, ERROR); }else{ returnMap.put(RESULT, SUCCESS); } return returnMap; } /** * 校验改分组下面是否有字典内容 * @param request * @param response * @param id * @return * @throws Exception */ @RequestMapping(value="existObject",method=RequestMethod.GET) @ResponseBody public Map<String,String> existObject( @RequestParam(required = false) String id)throws Exception{ Map<String,String>resultMap = new HashMap<String,String>(); int count = 0; count = dictionaryService.findDictionaryObjectByGroupId(id).size(); if(count >0){ resultMap.put(RESULT, ERROR); return resultMap; } resultMap.put(RESULT, SUCCESS); return resultMap; } /** * 把josn转成的map再转成List<DictionaryGroupsObject> * 工具方法 * @param map * @param todo(insert update delete) * @return */ @SuppressWarnings("unchecked") public List<DictionaryGroupsObject> getListFromJosn( Map<String, Object> map, String todo) { List<Map<String, Object>> dicMap = (List<Map<String, Object>>) map .get(todo); List<DictionaryGroupsObject> dicList = new ArrayList<DictionaryGroupsObject>(); for (Map<String, Object> map2 : dicMap) { DictionaryGroupsObject dicObject = new DictionaryGroupsObject(); if (!todo.equals("insert")) { dicObject.setId((String) map2.get("id")); } dicObject.setGroupName((String) map2.get("groupName")); dicObject.setGroupCode((String) map2.get("groupCode")); dicList.add(dicObject); } return dicList; } }
字典条目实现的action
package org.shield.module.web.controller.admin.dictionary; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.persistence.criteria.CriteriaBuilder.In; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.map.ObjectMapper; import org.shield.commons.dictionary.IDictionaryGroupService; import org.shield.commons.dictionary.IDictionaryService; import org.shield.commons.entity.dictionary.DictionaryGroupsObject; import org.shield.commons.entity.dictionary.DictionaryObject; import org.shield.commons.hibernate.dao.support.SearchMap; import org.shield.module.web.form.admin.dictionary.DictionaryObjectModel; import org.shield.omui.ComboDataModel; import org.shield.omui.GridDataModel; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * 数据字典管理 * * @author hhy * */ @Controller @RequestMapping("/admin/dic_content") @SuppressWarnings("unused") public class DictionaryObjcetController { private static final String ERROR="error"; private static final String RESULT="result"; private static final String SUCCESS="success"; @Resource private IDictionaryService dictionaryService; @Resource private IDictionaryGroupService dictionaryGroupService; @RequestMapping(method = RequestMethod.GET) public String view(Model model) { DictionaryObject dicObject = new DictionaryObject(); model.addAttribute("dicObject", dicObject); return "/admin/dictionary/dic_content"; } /** * 获取分组列表(key-value) * * @param request * @param response * @return * @throws Exception */ @RequestMapping(method = RequestMethod.GET, value = "groupList") @ResponseBody public List<DictionaryGroupsObject> groupList() throws Exception { List<DictionaryGroupsObject> resultList = new ArrayList<DictionaryGroupsObject>(); resultList = dictionaryGroupService.findAll(); return resultList; } /** * 获取数据字典分页信息 * * @param request * @param response * @param model * @return * @throws Exception */ @RequestMapping(value = "list", method = RequestMethod.GET) @ResponseBody public GridDataModel<DictionaryObjectModel> dicPage( HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) GridDataModel<DictionaryObjectModel> model, @RequestParam(required = false) String groupId, @RequestParam(required = false) int limit, @RequestParam(required = false) int start) throws Exception { if (model == null) { model = new GridDataModel<DictionaryObjectModel>(); } int total = 0; SearchMap map = dictionaryService.createSearchMap(); if (groupId != null && !groupId.equals("")) { map.eq("groups.id", groupId); } map.orderBy("priority", true); total = (int) dictionaryService.getTotalCountByMap(map); List<DictionaryObject> dicList = new ArrayList<DictionaryObject>(); List<DictionaryObjectModel> dicModelList = new ArrayList<DictionaryObjectModel>(); dicList = dictionaryService.findPageByMap(start, limit, map); // 转成页面model for (DictionaryObject dictionaryObject : dicList) { dicModelList.add(new DictionaryObjectModel(dictionaryObject)); } model.setRows(dicModelList); model.setTotal(total); return model; } /** * 处理数据字典的 增 删 改 * * @param request * @param response * @param formData * @return * @throws Exception */ @SuppressWarnings({ "unchecked" }) @RequestMapping(value = "save", method = RequestMethod.POST) @ResponseBody public Map<String, String> save(@RequestParam(required = false) String formData) throws Exception { Map<String, String> returnMap = new HashMap<String, String>(); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = (Map<String, Object>) mapper.readValue( formData, Map.class); // 处理添加 if (map.get("insert") != null && !(map.get("insert").toString()).equals("[]")) { List<DictionaryObject> dicList = getListFromJosn(map, "insert"); for (DictionaryObject dictionaryObject : dicList) { dictionaryService.createOrModify(dictionaryObject); } returnMap.put(SUCCESS, "添加成功"); } if (map.get("update") != null && !(map.get("update").toString()).equals("[]")) { List<DictionaryObject> dicList = getListFromJosn(map, "update"); for (DictionaryObject dictionaryObject : dicList) { dictionaryService.createOrModify(dictionaryObject); } returnMap.put(SUCCESS, "修改成功"); } if (map.get("delete") != null && !(map.get("delete").toString()).equals("[]")) { List<DictionaryObject> dicList = getListFromJosn(map, "delete"); for (DictionaryObject dictionaryObject : dicList) { dictionaryService.removeById(dictionaryObject.getId()); } returnMap.put(SUCCESS, "删除成功"); } return returnMap; } /** * 校验字典值是否存在 * @param request * @param response * @param value * @return * @throws Exception */ @RequestMapping(value = "existName", method = RequestMethod.GET) @ResponseBody public Map<String, String> exist( @RequestParam(required = false) String id, @RequestParam(required = false) String value) { Map<String, String> returnMap = new HashMap<String, String>(); int count = 0; //校验添加 if(id.equals("")){ String hql ="select count(*) from DictionaryObject dic where dic.value=?"; try { count =(int) dictionaryService.getTotalCountByHQL(hql,new String[]{value}); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(count>0){ returnMap.put(RESULT, ERROR); }else{ returnMap.put(RESULT, SUCCESS); } return returnMap; } //校验修改 if (value != null && !value.equals("")) { String hql ="select count(*) from DictionaryObject dic where dic.value=?"; try { count =(int) dictionaryService.getTotalCountByHQL(hql,new Object[]{value}); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(count>1){ returnMap.put(RESULT, ERROR); }else{ returnMap.put(RESULT, SUCCESS); } return returnMap; } /** * 把josn转成的map再转成List<DictionaryObject> * 工具方法 * @param map * @param todo(insert update delete) * @return */ @SuppressWarnings("unchecked") public List<DictionaryObject> getListFromJosn( Map<String, Object> map, String todo) { List<Map<String, Object>> dicMap = (List<Map<String, Object>>) map .get(todo); List<DictionaryObject> dicList = new ArrayList<DictionaryObject>(); for (Map<String, Object> map2 : dicMap) { DictionaryObject dicObject = new DictionaryObject(); String groupId =""; if(todo.equals("delete")){ dicObject.setId((String) map2.get("id")); dicList.add(dicObject); return dicList; } if (!todo.equals("insert")) { dicObject.setId((String) map2.get("id")); } try { groupId = dictionaryGroupService.getDictionaryGroupIdByGroupCode((String) map2.get("groupCode")); dicObject.setGroups(dictionaryGroupService.findById(groupId)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(map2.get("priority") instanceof String){ dicObject.setPriority(Integer.parseInt((String)map2.get("priority"))); } if(map2.get("priority") instanceof Integer){ dicObject.setPriority((Integer)map2.get("priority")); } dicObject.setName((String)map2.get("name")); dicObject.setValue((String)map2.get("value")); dicList.add(dicObject); } return dicList; } }
工具类 在action中转换 json
package org.shield.omui; import java.util.ArrayList; import java.util.List; /** * omGrid组件 * 只包装了数据的总条数total和所有数据集合rows,这样包装是为了前台omGrid组件能够识别返回的JSON个数数据。它需要的格式是:{"total":15,"rows":[{childJSON}]} * 将数据包装成GridDataModel格式之后再使用JSON-lib包的工具类JSONObject.fromObject(model) 生成json数据,最好返写回前台,完成omGrid数据的展示。 * @author zzluo * * @param <T> */ public class GridDataModel<T> { /** * 显示总数 */ private long total; /** * 行数据 */ private List<T> rows = new ArrayList<T>(); public List<T> getRows() { return rows; } public void setRows(List<T> rows) { this.rows = rows; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } }