1.前台html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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>丰缘管理系统 - 顺丰速运集团</title> <%@include file="../header.jsp"%> </head> <body> <table id="function_tb" class="easyui-treegrid" treeField="funcName"> </table> <div id="dlg" class="easyui-dialog" style="width: 500px; height: 250px; padding: 10px 30px;" title="添加功能" buttons="#dlg-buttons" closed="true"> <form id="ff" action="../service/func/add" method="post"> <table> <tr> <td>上级菜单:</td> <td><select class="easyui-combotree" id="add_select" url = "../service/func/allTree" name="parentId" style="width: 156px;" /></td> </tr> <tr> <td>功能名称:</td> <td><input type="text" name="funcName" style="width: 350px;" /></td> </tr> <tr> <td>功能路径:</td> <td><input type="text" name="url" style="width: 350px;" /></td> </tr> </table> </form> </div> <div id="dlg-buttons"> <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="addFunc()">确定</a> <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$(‘#dlg‘).dialog(‘close‘)">取消</a> </div> <script type="text/javascript" src="<%=request.getContextPath()%>/js/admin/function.js"></script> </body> </html>
2.前台js
/** * 初始化界面 */ var dataGrid; var rowEditor = undefined; $(function() { hideDialog(); dataGrid = $("#function_tb") .treegrid( { url : "../service/func/all",// 加载的URL idField : "id", method : "GET", treeField : "funcName", pagination : false,// 显示分页 fit : true,// 自动补全 fitColumns : true, singleSelect : true, iconCls : "icon-save",// 图标 columns : [ [ // 每个列具体内容 { field : ‘id‘, title : ‘编号‘, align : ‘center‘, width : 100, }, { field : ‘funcName‘, title : ‘功能名称‘, align : ‘center‘, width : 100, editor : ‘text‘ }, { field : ‘url‘, title : ‘功能路径‘, align : ‘center‘, width : 100, editor : ‘text‘ }, { field : ‘createTm‘, title : ‘创建时间‘, align : ‘center‘, width : 100 }, { field : ‘modifiedTm‘, title : ‘修改时间‘, align : ‘center‘, width : 100 }, { field : ‘isDelete‘, title : ‘是否禁用‘, align : ‘center‘, width : 100, editor : { type : ‘checkbox‘, options : { on : ‘1‘, off : ‘0‘ } }, formatter : function(value, row, index) { if (value == ‘0‘) { return ‘<span style="color:green">正常</span>‘; } else { return ‘<span style="color:red">禁用</span>‘; } } } ] ], toolbar : [ // 工具条 { text : "增加", iconCls : "icon-add", handler : function() {// 回调函数 openDialog(); } }, { text : "删除", iconCls : "icon-remove", handler : function() { var rows = dataGrid .treegrid(‘getSelections‘); if (rows.length <= 0) { $.messager.alert(‘警告‘, ‘您没有选择‘, ‘error‘); } else if (rows.length > 1) { $.messager.alert(‘警告‘, ‘不支持批量删除‘, ‘error‘); } else { $.messager .confirm( ‘确定‘, ‘您确定要删除吗‘, function(t) { if (t) { $ .ajax({ url : ‘../service/func/del‘, method : ‘POST‘, data : rows[0], dataType : ‘json‘, success : function( r) { if (r.code == "1") { dataGrid .treegrid(‘acceptChanges‘); $.messager .show({ msg : r.msg, title : ‘成功‘ }); editRow = undefined; dataGrid .treegrid(‘reload‘); } else { dataGrid .treegrid( ‘beginEdit‘, editRow); $.messager .alert( ‘错误‘, r.msg, ‘error‘); } dataGrid .treegrid(‘unselectAll‘); } }); } }) } } }, { text : "修改", iconCls : "icon-edit", handler : function() { var rows = dataGrid .treegrid(‘getSelections‘); if (rows.length == 1) { if (rowEditor == undefined) { //var index = dataGrid.treegrid(‘getRowIndex‘, rows[0]); var index = rows[0].id; rowEditor = index; dataGrid.treegrid(‘unselectAll‘); dataGrid.treegrid(‘beginEdit‘, index); } } } }, { text : "保存", iconCls : "icon-save", handler : function() { dataGrid.treegrid(‘endEdit‘, rowEditor); rowEditor = undefined; } }, { text : "取消编辑", iconCls : "icon-redo", handler : function() { dataGrid.treegrid(‘cancelEdit‘, rowEditor); rowEditor = undefined; } } ], onAfterEdit : function(rowIndex, rowData, changes) { var inserted = dataGrid.treegrid(‘getChanges‘, ‘inserted‘); var updated = dataGrid.treegrid(‘getChanges‘, ‘updated‘); if (inserted.length < 1 && updated.length < 1) { editRow = undefined; dataGrid.treegrid(‘unselectAll‘); return; } var url = ‘‘; if (inserted.length > 0) { url = ‘../service/func/add‘; } if (updated.length > 0) { url = ‘../service/func/update‘; } $.ajax({ url : url, method : "POST", data : rowIndex, dataType : ‘json‘, success : function(r) { if (r.code=="1") { dataGrid .treegrid(‘acceptChanges‘); $.messager.show({ msg : r.msg, title : ‘成功‘ }); editRow = undefined; dataGrid.treegrid(‘reload‘); } else { /* datagrid.treegrid(‘rejectChanges‘); */ dataGrid.treegrid(‘beginEdit‘, editRow); $.messager.alert(‘错误‘, r.msg, ‘error‘); } dataGrid.treegrid(‘unselectAll‘); } }); }, onDblClickCell : function(index, field, value) { if (rowEditor == undefined) { dataGrid.treegrid(‘beginEdit‘, field.id); rowEditor = field.id; } } }); }); var editingId; function edit() { if (editingId != undefined) { dataGrid.treegrid(‘select‘, editingId); return; } var row = dataGrid.treegrid(‘getSelected‘); if (row) { editingId = row.id; dataGrid.treegrid(‘beginEdit‘, editingId); } } function save() { if (editingId != undefined) { var t = $("#function_tb"); t.treegrid(‘endEdit‘, editingId); editingId = undefined; var persons = 0; var rows = t.treegrid(‘getChildren‘); for ( var i = 0; i < rows.length; i++) { var p = parseInt(rows[i].persons); if (!isNaN(p)) { persons += p; } } var frow = t.treegrid(‘getFooterRows‘)[0]; frow.persons = persons; t.treegrid(‘reloadFooter‘); } } function cancel() { if (editingId != undefined) { dataGrid.treegrid(‘cancelEdit‘, editingId); editingId = undefined; } } function hideDialog(){ $(‘#dlg‘).dialog(‘close‘); } function openDialog(){ //$("#add_select").attr(‘url‘,‘../service/func/allTree‘); $(‘#add_select‘).combotree({ url : ‘../service/func/allTree‘ }); $(‘#dlg‘).dialog(‘open‘); } function addFunc(){ $(‘#ff‘).form(‘submit‘,{ url:‘../service/func/add‘, success:function(data){ var r = JSON.parse(data); if(r.code=="1"){ $.messager.show({ msg : r.msg, title : ‘成功‘ }); hideDialog(); dataGrid .treegrid(‘reload‘); }else{ $.messager.alert( ‘错误‘, r.msg, ‘error‘); hideDialog(); dataGrid .treegrid(‘reload‘); } } }); }
3.后台controller中
/** * */ package com.sf.fys.controller.role; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.google.gson.Gson; import com.sf.fys.config.LogAppender; import com.sf.fys.controller.BaseController; import com.sf.fys.data.Res; import com.sf.fys.data.TreeGrid; import com.sf.fys.model.Function; import com.sf.fys.result.ListResultMsg; import com.sf.fys.result.ResultResponse; import com.sf.fys.result.ReturnCode; import com.sf.fys.result.StringResult; import com.sf.fys.service.role.FunctionService; /** * @author sfit0512 * */ @RestController public class FuncController extends BaseController { Logger log = Logger.getLogger(LogAppender.ADMIN); @Autowired private FunctionService funcService; @RequestMapping(value = "/func/allTree", method = RequestMethod.POST) @ResponseBody public String getFuncsTree(HttpServletRequest request, HttpServletResponse response) throws Exception { Gson gson = new Gson(); List<Function> list = funcService.getFuncs(); if(!list.isEmpty()){ String ret = gson.toJson(list); ret = ret.replace("funcName", "text"); return ret; } return FAIL; } @RequestMapping(value = "/func/roleTree", method = RequestMethod.POST) @ResponseBody public String getFuncsTreeByRole(HttpServletRequest request, HttpServletResponse response) throws Exception { String roleId = request.getParameter("roleId"); Gson gson = new Gson(); List<Function> list = funcService.getFuncsByRole(Long.parseLong(roleId)); if(!list.isEmpty()){ String ret = gson.toJson(list); ret = ret.replace("funcName", "text"); return ret; } return FAIL; } /** * 查询所有功能权限 * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/func/all", method = RequestMethod.GET) @ResponseBody public String getFuncs(HttpServletRequest request, HttpServletResponse response) throws Exception { Gson gson = new Gson(); //List<Function> list = funcService.getFunctions(); List<Function> list = funcService.getFuncs(); TreeGrid<Function> treeGrid = new TreeGrid<Function>(); treeGrid.setTotal(String.valueOf(list.size())); treeGrid.setRows(list); if(!list.isEmpty()){ String ret = gson.toJson(treeGrid); return ret; } return FAIL; } /** * 添加功能权限 * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/func/add", method = RequestMethod.POST) @ResponseBody public Res addFunc(HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = request.getParameter("funcName"); String parentId = request.getParameter("parentId"); String url = request.getParameter("url"); if(parentId==null||"".equals(parentId)){ parentId = "0";//为空则设为根目录 } Function func = new Function(); func.setFuncName(funcName); func.setParentId(Long.parseLong(parentId)); func.setUrl(url); func.setIsDelete(‘0‘); int ret = funcService.addFunc(func); if(ret>0){ return success(); } return fail(); } /** * 修改功能权限 * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/func/update", method = RequestMethod.POST) @ResponseBody public Res updateFunc(HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = request.getParameter("funcName"); String parentId = request.getParameter("parentId"); String url = request.getParameter("url"); String isDelete = request.getParameter("isDelete"); String id = request.getParameter("id"); //如果不选择就是一级菜单 if("".equals(parentId)){ parentId = "0"; } Function func = new Function(); func.setFuncName(funcName); func.setParentId(Long.parseLong(parentId)); func.setUrl(url); func.setIsDelete(isDelete.charAt(0)); func.setId(Long.parseLong(id)); int ret = funcService.updateFunc(func); if(ret>0){ return success(); } return fail(); } /** * 删除角色 * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/func/del", method = RequestMethod.POST) @ResponseBody public Res deleteFunc(HttpServletRequest request, HttpServletResponse response) throws Exception { String id = request.getParameter("id"); int ret = funcService.deleteFunc(Long.parseLong(id)); if(ret>0){ return success(); } return fail(); } @RequestMapping(value = "/func/getUserFunc", method = RequestMethod.POST) @ResponseBody public ResultResponse getUserFunc(HttpServletRequest request, HttpServletResponse response) throws Exception { String userId = request.getParameter("userId"); log.info("getUserFunc|userId="+userId); if(StringUtils.isEmpty(userId)){ return new StringResult(ReturnCode.FAIL, ReturnCode.get(ReturnCode.FAIL), ""); } List<Function> list = funcService.getUserFunc(Long.parseLong(userId)); if(null != list){ return new ListResultMsg<Function>(ReturnCode.SUCCESS, "", list); }else{ return new StringResult(ReturnCode.FAIL, ReturnCode.get(ReturnCode.FAIL), ""); } } } 4.后台service /** * */ package com.sf.fys.service.role; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sf.fys.mapper.role.FunctionMapper; import com.sf.fys.model.Function; /** * 功能权限管理 * @author sfit0512 * */ @Service public class FunctionService { private static Logger log = Logger.getLogger(FunctionService.class); @Autowired private FunctionMapper functionMapper; /** * 查询所有功能列表 * @return */ public List<Function> getFuncs() { List<Function> list = functionMapper.getFuncs(); List<Function> newList = getTree(list); return newList; } /** * 根据角色查询功能列表 * @param roleId * @return */ public List<Function> getFuncsByRole(long roleId) { List<Function> list = functionMapper.getFuncsByRole(roleId); List<Function> newList = getTree(list); return newList; } /** * 转成树形集合 * @param list * @return */ public List<Function> getTree(List<Function> list) { List<Function> nodeList = new ArrayList<Function>(); for (Function f : list) { boolean mark = false; for (Function f2 : list) { if (f.getParentId() == f2.getId()) { mark = true; if (f2.getChildren() == null) { f2.setChildren(new ArrayList<Function>()); } f2.getChildren().add(f); break; } } if (!mark) { nodeList.add(f); } } return nodeList; } /** * 添加功能 * @param func * @return */ public int addFunc(Function func) { return functionMapper.addFunction(func); } /** * 修改功能 * @param func * @return */ public int updateFunc(Function func) { return functionMapper.updateFunction(func); } /** * 删除功能 * @param id * @return */ public int deleteFunc(long id) { return functionMapper.delFunction(id); } /** * 根据用户编号查询该用户拥有的功能权限 * @param id * @return */ public List<Function> getUserFunc(long userId) { log.info("getUserFunc|id=" + userId); // 1.根据用户id查询该用户拥有的角色 // 2.遍历所有角色,查询对应的功能id(去掉重复) List<Function> list = functionMapper.getFuncByUser(userId); if(list!=null){ log.info("getUserFunc|list.size="+list.size()); } return list; } }
5.mapper
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.sf.fys.mapper.role.FunctionMapper"> <!-- 查询所有功能 --> <select id="getFuncs" resultType="com.sf.fys.model.Function"> select func_id as id,func_name as funcName,create_tm as createTm,modified_tm as modifiedTm,parent_id as parentId,url,is_delete as isDelete from Functions where is_delete = 0 </select> <select id="getFuncsByRole" resultType="com.sf.fys.model.Function"> select f.func_id as id,f.func_name as funcName,f.create_tm as createTm,f.modified_tm as modifiedTm,f.parent_id as parentId,f.url,f.is_delete as isDelete from Functions f, Role_Functions rf where f.func_id = rf.func_id and f.is_delete = 0 and rf.role_id = #{roleId,jdbcType=BIGINT}; </select> <!-- 查询所有父节点功能 --> <select id="getParentFunc" resultType="com.sf.fys.model.Function"> select func_id as id,func_name as funcName,create_tm as createTm,modified_tm as modifiedTm,parent_id as parentId,url,is_delete as isDelete from Functions where parent_id = 0; </select> <!-- 查询父功能下的所有子功能 --> <select id="getChildFunc" resultType="com.sf.fys.model.Function"> select func_id as id,func_name as funcName,create_tm as createTm,modified_tm as modifiedTm,parent_id as parentId,url,is_delete as isDelete from Functions where parent_id = #{id,jdbcType=BIGINT}; </select> <!-- 添加功能 --> <insert id="addFunction"> insert into Functions(FUNC_NAME,CREATE_TM,MODIFIED_TM,PARENT_ID,URL,IS_DELETE) values( #{funcName,jdbcType=VARCHAR}, now(), now(), #{parentId,jdbcType=BIGINT}, #{url,jdbcType=VARCHAR}, #{isDelete,jdbcType=CHAR} ) </insert> <!-- 修改功能 --> <update id="updateFunction"> update Functions set FUNC_NAME=#{funcName,jdbcType=VARCHAR}, MODIFIED_TM = now(), PARENT_ID = #{parentId,jdbcType=BIGINT}, URL = #{url,jdbcType=VARCHAR}, IS_DELETE = #{isDelete,jdbcType=CHAR} where FUNC_ID = #{id,jdbcType=BIGINT} </update> <!-- 删除功能 --> <delete id="delFunction"> <!-- delete from Function where FUNC_ID = #{id,jdbcType=BIGINT} --> update Functions set IS_DELETE = 1 where FUNC_ID = #{id,jdbcType=BIGINT} </delete> <!-- 查询某用户所有功能权限 --> <select id="getFuncByUser" resultType="com.sf.fys.model.Function"> select func_id as id,func_name as funcName,create_tm as createTm,modified_tm as modifiedTm,parent_id as parentId,url,is_delete as isDelete from Functions where func_id in (select distinct(func_id) from Role_Functions where role_id in ( select role_id from Role_User where user_id = #{userId,jdbcType=BIGINT})) and is_delete =0 </select> </mapper>