接上文希望从一张表(tb_role_info 用户角色表)的CRUD展开spring mvc的项目实战化魅力。
开发技术选型:spring mvc+freemarker+bootstrap+mybatis+mysql。
项目目录结构:
(1)业务表 tb_role_info
-- ---------------------------- -- Table structure for `tb_role_info` 用户角色表 -- ---------------------------- DROP TABLE IF EXISTS `tb_role_info`; CREATE TABLE `tb_role_info` ( `id` int(11) NOT NULL AUTO_INCREMENT, `role_name` varchar(32) NOT NULL DEFAULT '' COMMENT '角色名称', `role_mark` varchar(255) DEFAULT '' COMMENT '角色备注', `creater_id` int(11) NOT NULL DEFAULT '0' COMMENT '记录创建者id', `created_at` timestamp NULL DEFAULT NULL COMMENT '创建日期', `updated_at` timestamp NULL DEFAULT NULL COMMENT '更新日期', `time_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '记录更新时间戳', PRIMARY KEY (`id`), KEY `tb_role_info_index` (`id`,`role_name`,`creater_id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='角色信息表';
(2)业务界面 role.html
<!DOCTYPE html> <html> <head> <#include "header.html" /> <link rel="stylesheet" type="text/css" href="../assets/backend/plugs/bootstrap-table/src/bootstrap-table.css?v=${version}"/> </head> <body> <#include "navbar.html" /> <div id="page-container"> <!-- BEGIN SIDEBAR --> <#include "menu.html" /> <!-- END SIDEBAR --> <!-- BEGIN RIGHTBAR --> <!-- END RIGHTBAR --> <div id="page-content"> <div id="wrap"> <div id="page-heading"> <ol class="breadcrumb"> <li><a href="#" title="icons">系统管理</a></li> <li class="active">角色信息</li> </ol> </div> <!-- container 内容显示区域begin--> <div class="container"> <div class='data_loading'></div> <div class="row"> <div class="col-xs-9" id="panel_list"> <div class="panel panel-gray"> <div class="panel-heading"> <h4> 角色信息 </h4> <div class="options"> <div class="btn-group" id="table_tools_bar"> <button type="button" class="btn btn-default dropdown-toggle btn-tools" data-toggle="dropdown" title="定制列显示"><i class="fa fa-th-list"></i> <span class="caret"></span></button> <button id="btn_role_refresh" type="button" class="btn btn-default btn-tools" title="角色刷新"><i class="fa fa-refresh"></i></button> <button id="btn_role_search" type="button" class="btn btn-default btn-tools" title="角色查询"><i class="fa fa-search"></i></button> </div> </div> <div class="options options-groups"> <a href="javascript:;" id="btn_role_delete" title="角色删除" style="display:none;"><i class="fa fa-times"></i> 删除</a> <a data-toggle="modal" href="#modalDialog" id="btn_role_edit" title="角色编辑"><i class="fa fa-edit"></i> 编辑</a> <a data-toggle="modal" href="#modalDialog" id="btn_role_add" title="角色添加"><i class="fa fa-pencil"></i> 添加</a> </div> </div> <div class="panel-body"> <div class="table-responsive"> <table id="table_role"></table> </div> <!-- add/edit modal-begin --> <div id="modalDialog" class="modal fade md-trigger" data-modal="md-fade-in-scale-up" tabindex="-1" role="dialog" aria-labelledby="modalLabel" data-keyboard="true" data-backdrop="static" aria-hidden="true"> <div id="modalBox" class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> ×</button> <h4 class="modal-title" id="modalLabel"></h4> </div> <div class="modal-body"> <form id="modalForm" class="form-horizontal" role="form" enctype="multipart/form-data"> <!-- 隐藏值存放区域 begin--> <input name="id" id="form_hidden_id" type="hidden"> <!-- 隐藏值存放区域 end--> <div class="form-group"> <label for="form_txt_roleName" class="col-sm-2 control-label">角色名称</label> <div class="col-sm-7"> <input id="form_txt_roleName" name="roleName" maxlength="32" placeholder="角色名称最多32个字符" required="" type="text" class="form-control"> </div> <div class="col-sm-3"> <p class="help-block">角色名称必填!</p> </div> </div> <div class="form-group"> <label for="form_txt_roleName" class="col-sm-2 control-label">角色权限</label> <div class="col-sm-10"> <table id="table_module" class="table table-bordered"> <thead> <tr> <th width="2%" style="padding: 10px"> </th> <th width="28%" style="padding: 10px"> 模块 </th> <th width="30%" style="padding: 10px"> 功能 </th> <th width="30%" style="padding: 10px"> 动作 </th> </tr> </thead> <#if moduleList??> <tbody> <#list moduleList as module> <#if module.id==1 && user['userRoleId']!=1> <#else> <tr> <td> <input type="checkbox" id="power_${module.id}" name="mod_${module.id}" value="${module.id}" onclick="checkModule(${module.id});" /> </td> <td> ${module.moduleCnName} </td> <td> <table width="100%"> <#if module.children??> <#list module.children as child> <tr> <td width="6%"><input type="checkbox" id="power_${child.id}" name="fun_${module.id}" value="${child.id}" onclick="checkFun(${module.id});" /></td> <td width="94%">${child.moduleCnName}</td> </tr> </#list> </#if> </table> </td> <td> <table width="100%"> <#if module.children??> <#list module.children as child> <#if child.children??> <#list child.children as subChild> <tr> <td width="6%"><input type="checkbox" id="power_${subChild.id}" name="act_${child.id}" value="${subChild.id}" onclick="checkAction(${child.id});"/></td> <td width="94%">${subChild.moduleCnName}</td> </tr> </#list> </#if> </#list> </#if> </table> </td> </tr> </#if> </#list> </tbody> </#if> </table> </div> </div> <div class="form-group"> <label for="form_txt_roleMark" class="col-sm-2 control-label"> 角色描述</label> <div class="col-sm-10"> <textarea id="form_txt_roleMark" name="roleMark" maxlength="255" placeholder="角色描述最多255个字符" class="form-control autosize"></textarea> </div> </div> </form> </div> <div class="modal-footer"> <button id="btn_modal_save" type="button" class="btn btn-primary"> 确定</button> <button type="button" class="btn btn-default" data-dismiss="modal"> 取消</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- add/edit modal-end --> </div> </div> </div> <div class="col-xs-3" id="panel_search" style="display: none"> <div class="panel panel-gray"> <div class="panel-heading"> <h4> 角色查询 </h4> </div> <div class="panel-body"> <form class="form-horizontal"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label for="search_txt_roleName" class="col-sm-4 control-label">角色名称</label> <div class="col-sm-8"> <input id="search_txt_roleName" type="text" class="form-control" placeholder="请输入关键字..."> </div> </div> </div> </div> </form> </div> <div class="panel-footer"> <div class="row"> <div class="col-sm-12 col-sm-offset-3"> <div class="btn-toolbar"> <button id="btn_submit_search" class="btn-primary btn">确定</button> <button id="btn_cancel_search" class="btn-default btn">取消</button> </div> </div> </div> </div> </div> </div> </div> </div> <!-- container 内容显示区域end--> </div> <!--wrap --> </div> </div> <!-- page-container --> <!-- page-content --> <#include "footer.html" /> </body> </html> <script type="text/javascript" charset="utf-8" src="../assets/backend/plugs/bootstrap-table/src/bootstrap-table.js?v=${version}"></script> <script type="text/javascript" charset="utf-8" src="../assets/backend/plugs/bootstrap-table/src/locale/bootstrap-table-zh-CN.js?v=${version}"></script> <script type="text/javascript" charset="utf-8" src="../assets/backend/js/sys_role.js?v=${version}"></script>
(3)业务界面逻辑 sys_role.js
/** * sys_role * 角色信息 * @author steven9801@163.com * @date 2015-11-19 */ (function ($) { $(document).ready(function () { /** * 初始化 */ init(); /** * 新建模态 */ $('#btn_role_add').click(function () { addModal() }); /** * 编辑模态 */ $('#btn_role_edit').click(function () { var rowList = dataGrid.bootstrapTable('getSelections'); var length = rowList.length; if (length == 0) { warningBox('请选择编辑对象.'); return false; } if (length > 1) { warningBox('只能编辑一项.'); return false; } editModal(rowList[0]); }); /** * 保存动作 */ $('#btn_role_save').click(function () { switch (dialogType) { case 'add': onAdd(); break; case 'edit': onEdit(); break; default: break; } }); /** * 删除 */ $('#btn_role_delete').click(function () { onDelete(); }); //-----------------常规事件----------begin-------// /** * 刷新 */ $('#btn_role_refresh').click(function () { dataGrid.bootstrapTable('destroy'); loadGrid(); }); /** * 展开 */ $('#btn_search_expand').click(function () { $(this).html(''); if(!searchStatus){ $('#search_more_panel').show('slow'); $(this).html('<i class="fa fa-angle-double-down"></i>'); searchStatus = true; } else{ $('#search_more_panel').hide('slow'); $(this).html('<i class="fa fa-angle-double-up"></i>'); searchStatus = false; } return false; }); /** * 提交查询 */ $('#btn_search_save').click(function () { dataGrid.bootstrapTable('destroy'); bindGrid(function (params) { var roleName = $('#search_txt_roleName').val(); role.pageSize = params.pageSize; role.pageStart = params.pageSize * (params.pageNumber - 1); role.sortName = params.sortName; role.sortOrder = params.sortOrder; if (roleName.length > 0) { role.roleName = roleName; } return JSON.stringify(role); }); }); //-----------------常规事件----------end-------// }); })(jQuery); /** * 全局变量 */ //--------------------------全局变量区---------------------------// var dataGrid = null; //列表对象 var dialogType = 'add'; var role = {}; var lock = false; //防止重复提交 var searchStatus = false; //查询面板状态 //--------------------------全局变量区---------------------------// /** * 初始化 */ function init() { loadGrid(); $("#form_modal .modal-body").css({ height: "650px", overflowX: "hidden", overflowY: "auto" }); $('textarea.autosize').autosize({ append: "\n" }); }; /** * * 加载列表 * */ function loadGrid() { bindGrid(function (params) { return JSON.stringify({ pageSize: params.pageSize, pageStart: params.pageSize * (params.pageNumber - 1), sortName: params.sortName, sortOrder: params.sortOrder }); }); return false; }; /** * 绑定列表 */ function bindGrid(callBack) { dataGrid = $('#role_table').bootstrapTable({ method: 'POST', contentType: 'application/json;charset=utf-8', url: '../admin/role', height: 500, striped: true, pagination: true, sidePagination: 'server', pageSize: 25, pageList: [25, 50, 100, 200], showExport: true, sortName: 'createdAt', sortOrder: 'desc', minimunCountColumns: 2, formatLoadingMessage: function () { return '<img src="../backend/images/loading.gif"/>'; }, queryParams: callBack, columns: [ { field: 'state', checkbox: true }, { field: 'roleName', title: '角色名称', align: 'left', valign: 'middle', sortable: true }, { field: 'createdAt', title: '创建时间', align: 'center', valign: 'middle', sortable: true }, { field: 'operate', title: '操作', align: 'left', valign: 'middle', sortable: false, formatter: operateFormatter, events: operateEvents } ] }); }; /** * 格式化操作列 * */ function operateFormatter(value, row, index) { var content = []; content.push(' <a class="view" data-toggle="modal" href="#form_modal" title="角色查看"><i class="fa fa-eye"></i></a>'); content.push(' <a class="edit" data-toggle="modal" href="#form_modal" title="角色编辑"><i class="fa fa-edit"></i></a>'); content.push(' <a class="delete" href="javascript:void(0)" title="角色删除"><i class="fa fa-times"></i></a>'); return content.join(''); }; /** * 操作列事件 */ window.operateEvents = { 'click .view': function (e, value, row, index) { viewModal(row); return false; }, 'click .edit': function (e, value, row, index) { editModal(row); return false; }, 'click .delete': function (e, value, row, index) { if (lock) return false; lock = true; if (userToken.id != row.createrId) { lock = false; warningBox('对不起,您无权删除该角色.'); return false; } var ids = []; ids.push(row.id); var params = {}; params.ids = ids; deleteModal(params); } }; /** * 显示模态 */ function showModal(action, title, width) { dialogType = action; $('.modal-footer').show(); $('#form_modal #form_modal_title').html(title); $('#form_modal_dialog').css({ width: width }); $('select,textarea,input').prop('disabled', false); $('#back-to-top').trigger('click'); return false; }; /** * 绑定模态 */ function bindModal(row) { $('#form_hidden_id').val(row.id); $('#form_hidden_createrId').val(row.createrId); $('#form_txt_roleName').val(row.roleName); $('#form_txt_roleMark').val(row.roleMark); $("input[id^='power_']").removeAttr("checked"); var moduleIdList = row.moduleIdList; for (var i in moduleIdList) { var id = moduleIdList[i]; $("input[id='power_" + id + "']").prop("checked", true); } }; /** * 查看模态 */ function viewModal(row) { showModal('view', '角色查看', '60%'); bindModal(row); $('select,textarea,input:not(.fixed-table-container input)').prop('disabled', true); $('#search_panel select,#search_panel input').prop('disabled', false); $('#table_tools_bar').find('input').prop('disabled', false); $('.modal-footer').hide(); return false; }; /** * 编辑模态 */ function editModal(row) { role = row; if (userToken.id != row.createrId) { pauseModal('#form_modal'); warningBox('对不起,您无权编辑该角色.'); return false; } showModal('edit', '角色编辑', '60%'); bindModal(row); return false; }; /** * 新建模态 */ function addModal() { showModal('add', '角色新建', '60%'); $('input[type=text],input[type=hidden],input[type=number],textarea').val(''); $('select option').eq(0).prop('selected', true); $("input[id^='power_']").prop('checked', false); return false; }; /** * 验证表单 */ function checkForm() { if (lock) return false; lock = true; var roleName = $("#form_txt_roleName").val(); if (roleName.length == 0) { warningBox("角色名称不能为空."); lock = false; return false; } if (roleName.length > 32) { warningBox("角色名称最多32个字符."); lock = false; return false; } if ($("input[id^='power_']:checkbox:checked").length == 0) { warningBox("请选择权限."); lock = false; return false; } var roleMark = $("#form_txt_roleMark").val(); if (roleMark.length > 255) { warningBox("角色描述最多255个字符."); lock = false; return false; } var moduleIdList = []; $("input[id^='power_']:checkbox:checked").each(function () { var id = parseInt($(this).val()); moduleIdList.push(id); }); role.roleName = roleName; role.roleMark = roleMark; role.moduleIdList = moduleIdList; return true; }; /** * 角色添加 */ function onAdd() { if (!checkForm()) { return false; } $('.data-loading').show(); var task = new DelayedTask(function () { $.ajax({ cache: false, type: "POST", dataType: "json", contentType: "application/json;charset=utf-8", url: "../admin/role.add", data: JSON.stringify(role), timeout: 30000, success: function (data) { if (data) { $(".data-loading").hide(); var code = data.code; if (code != 0) { dangerBox(data.message); lock = false; return false; } lock = false; $('#form_modal').modal('hide') successBox('角色新建成功.'); $('#btn_role_refresh').trigger('click'); } return false; }, error: function (e) { if (e.status == 404) { window.location = "../404.html"; } else if (e.status == 500) { window.location = "../500.html"; } } }); }); task.delay(500); return false; }; /** * 角色编辑 */ function onEdit() { if (!checkForm()) { return false; } $('.data-loading').show(); var task = new DelayedTask(function () { $.ajax({ cache: false, type: "POST", dataType: "json", contentType: "application/json;charset=utf-8", url: "../admin/role.edit", data: JSON.stringify(role), timeout: 30000, success: function (data) { if (data) { $(".data-loading").hide(); var code = data.code; if (code != 0) { dangerBox(data.message); lock = false; return false; } lock = false; $('#form_modal').modal('hide') successBox('角色编辑成功.'); $('#btn_role_refresh').trigger('click'); } return false; }, error: function (e) { if (e.status == 404) { window.location = "../404.html"; } else if (e.status == 500) { window.location = "../500.html"; } } }); }); task.delay(500); return false; }; /** * 角色删除 */ function onDelete() { if (lock) return false; lock = true; var ids = []; var rowList = dataGrid.bootstrapTable('getSelections'); var length = rowList.length; if (length == 0) { warningBox('请选择删除对象.'); lock = false; return false; } var flag = false; for (var i in rowList) { var row = rowList[i]; var createrId = row.createrId; if (userToken.id != createrId) { flag = true; } var id = row.id; ids.push(id); } if (flag) { warningBox('对不起,您无权删除该角色.'); lock = false; return false; } var params = {}; params.ids = ids; deleteModal(ids); return false; }; /** * 删除模态 */ function deleteModal(ids) { confirmBox('您确定要删除吗?!', function (result) { if (result) { $('.data-loading').show(); $.ajax({ cache: false, type: 'POST', dataType: 'json', contentType: 'application/json;charset=utf-8', url: '../admin/role.delete', data: JSON.stringify(ids), timeout: 30000, success: function (data) { if (data) { $('.data-loading').hide(); var code = data.code; if (code != 0) { dangerBox(data.message); lock = false; return false; } lock = false; successBox('角色删除成功.'); $('#btn_role_refresh').trigger('click'); } return false; }, error: function (e) { if (e.status == 404) { window.location = '../404.html'; } else if (e.status == 500) { window.location = '../500.html'; } } }); } else { lock = false; } }); return false; }; /** * 选择模块 */ function checkModule(moduleId) { $("input[name='fun_" + moduleId + "']").each(function () { if ($(this).is(":checked") == true) { $(this).prop("checked", false) } else { $(this).prop("checked", true); } }); }; /** * 选择功能 */ function checkFun(moduleId) { var funLength = $("input[name='fun_" + moduleId + "']:checkbox:checked").length; if (funLength != 0) { $("input[name='mod_" + moduleId + "']").prop("checked", true); } else { $("input[name='mod_" + moduleId + "']").prop("checked", false); } }; /** * 选择动作 */ function checkAction(funId) { var actLength = $("input[name='act_" + funId + "']:checkbox:checked").length; if (actLength != 0) { $("input[id='power_" + funId + "']").prop("checked", true); } else { $("input[id='power_" + funId + "']").prop("checked", false); } };
4)业务控制器 RoleController.java
package com.hwabao.controller; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; 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.servlet.ModelAndView; import com.hwabao.common.CommanUtil; import com.hwabao.common.EntityGrid; import com.hwabao.common.SessionValidate; import com.hwabao.model.ModuleInfo; import com.hwabao.model.RoleInfo; import com.hwabao.model.RoleModule; import com.hwabao.model.UserInfo; import com.hwabao.service.IModuleInfoService; import com.hwabao.service.IRoleInfoService; import com.hwabao.service.IRoleModuleService; import com.hwabao.service.ITransactionalService; /** * * @ClassName: RoleController * @Description: 角色控制器 * @author steven9801@163.com * @date 2015-4-21 下午04:36:24 * */ @Controller @RequestMapping("/admin") public class RoleController extends BaseController { private static final Logger logger = LoggerFactory.getLogger(RoleController.class); @Autowired private HttpServletRequest request; @Autowired private IRoleInfoService roleInfoService; @Autowired private IModuleInfoService moduleInfoService; @Autowired private IRoleModuleService roleModuleService; @Autowired private ITransactionalService transactionalService; /** * 角色界面 */ @SessionValidate(comment="角色界面") @RequestMapping(value = "/role", method = RequestMethod.GET) public ModelAndView index() throws Exception { UserInfo user = this.appContext.getCurrentUser(request); if(user!=null) { ModelAndView mv = this.handlerModelView(user,"backend/role"); ModuleInfo model = new ModuleInfo(); model.moduleSortAsc(); List<ModuleInfo> list = moduleInfoService.selectModuleInfo(model); List<ModuleInfo> moduleList = this.toObjectModuleTree(list,0); mv.addObject("moduleList", moduleList); return mv; } return this.handlerModelView("backend/login"); } @SessionValidate(comment="角色列表") @RequestMapping(value = "/role", method = RequestMethod.POST) @ResponseBody public String grid(@RequestBody RoleInfo roleInfo) throws Exception { UserInfo user = this.appContext.getCurrentUser(request); if(user==null) { return this.handlerSuccessMessage("../admin/login"); } try { RoleInfo roleInfoModel = findRoleInfo(roleInfo); int total = roleInfoService.getRoleInfoSearchCount(roleInfoModel); List<RoleInfo> roleList = roleInfoService.searchRoleInfo(roleInfoModel); EntityGrid<RoleInfo> entityGrid = null; if(roleList!=null&&roleList.size()>0) { for(RoleInfo role:roleList) { List<Integer> moduleIdList = new ArrayList<Integer>(); RoleModule roleModule = new RoleModule(); roleModule.setRoleId(role.getId()); List<RoleModule> roleModuleList = roleModuleService.selectRoleModule(roleModule); for(RoleModule module:roleModuleList) { moduleIdList.add(module.getModuleId()); } role.setModuleIdList(moduleIdList); } entityGrid = new EntityGrid<RoleInfo>(); entityGrid.rows = roleList; entityGrid.total = total; } else { entityGrid = new EntityGrid<RoleInfo>(); } return this.handlerResponseMessage(entityGrid); } catch (Exception e) { logger.debug(e.getMessage().toString()); return this.handlerFailMessage(e.getMessage().toString()); } } /** * 角色添加 */ @SessionValidate(comment="角色添加") @RequestMapping(value = "/role.add", method = RequestMethod.POST,consumes="application/json") @ResponseBody public String add(@RequestBody RoleInfo roleInfo) throws Exception { UserInfo user = this.appContext.getCurrentUser(request); if(user==null) { return this.handlerSuccessMessage("../admin/login"); } try { String roleName = roleInfo.getRoleName(); RoleInfo model = new RoleInfo(); model.setRoleName(roleName); RoleInfo cl = roleInfoService.getRoleInfo(model); if(cl!=null) { throw new Exception("角色名称重复."); } roleInfo.setCreatedAt(CommanUtil.getCurrentDatetime()); roleInfo.setCreaterId(user.getId()); int change = transactionalService.insertRoleInfo(roleInfo); if(change==0) { throw new Exception("角色新建失败."); } this.logSuccess("角色新建"); return this.handlerSuccessMessage("../admin/role"); } catch (Exception e) { this.logFailed("角色新建"); logger.debug(e.getMessage().toString()); return this.handlerFailMessage(e.getMessage().toString()); } } /** * 角色编辑 */ @SessionValidate(comment="角色编辑") @RequestMapping(value = "/role.edit", method = RequestMethod.POST,consumes="application/json") @ResponseBody public String edit(@RequestBody RoleInfo roleInfo) throws Exception { UserInfo user = this.appContext.getCurrentUser(request); if(user==null) { return this.handlerSuccessMessage("../admin/login"); } try { int change = transactionalService.updateRoleInfo(roleInfo); if(change==0) { throw new Exception("角色编辑失败."); } this.logSuccess("角色编辑"); return this.handlerSuccessMessage("../admin/role"); } catch (Exception e) { this.logFailed("角色编辑"); logger.debug(e.getMessage().toString()); return this.handlerFailMessage(e.getMessage().toString()); } } /** * 角色删除 */ @SessionValidate(comment="角色删除") @RequestMapping(value = "/role.delete",method = RequestMethod.POST,consumes="application/json") @ResponseBody public String delete(@RequestBody List<Integer> params) throws Exception { UserInfo user = this.appContext.getCurrentUser(request); if(user==null) { return this.handlerSuccessMessage("../admin/login"); } try { if(params.size()==0) { throw new Exception("params参数非空."); } List<RoleInfo> roleList = new ArrayList<RoleInfo>(); for(Integer roleid : params) { RoleInfo roleInfo = new RoleInfo(); roleInfo.setId(roleid); roleList.add(roleInfo); } int change = transactionalService.deleteRoleInfo((ArrayList<RoleInfo>)roleList); if(change==0) { throw new Exception("角色删除失败."); } this.logSuccess("角色删除"); return this.handlerSuccessMessage("../admin/role"); } catch (Exception e) { this.logFailed("角色删除"); logger.debug(e.getMessage().toString()); return this.handlerFailMessage(e.getMessage().toString()); } } /** * 封装前端查询角色条件的方法 * @param roleInfo * @return */ private RoleInfo findRoleInfo(RoleInfo roleInfo) { if(roleInfo.getSortName()!=null&&roleInfo.getSortOrder()!=null) { String sortName = roleInfo.getSortName(); String sortOrder = roleInfo.getSortOrder(); roleInfo.setOrderBy(sortName, sortOrder); } if(roleInfo.getRoleName() != null) { roleInfo.roleNameLike(roleInfo.getRoleName()); } return roleInfo; } }
(5)业务实体层 RoleInfo.java
package com.hwabao.model; import java.util.List; import com.hwabao.common.VoBase; /** * @author steven9801@163.com */ public class RoleInfo extends VoBase<RoleInfo> { private static final long serialVersionUID = 1L; /** * */ private Integer id; /** * 角色名称 */ private String roleName; /** * 角色备注 */ private String roleMark; /** * 记录创建者id */ private Integer createrId; /** * */ private String updatedAt; /** * */ private String createdAt; /** * 记录更新时间戳 */ private String timeStamp; //---------------------扩展属性-----------begin-----------// private List<Integer> moduleIdList; public List<Integer> getModuleIdList() { return moduleIdList; } public void setModuleIdList(List<Integer> moduleIdList) { this.moduleIdList = moduleIdList; } //---------------------扩展属性-----------end-----------// public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public void idDesc() { _setOrder("id", "DESC"); } public void idAsc() { _setOrder("id", "ASC"); } public void idMax(Integer max) { _setRangeMax("id", String.valueOf(max)); } public void idMin(Integer min) { _setRangeMin("id", String.valueOf(min)); } public void idEqual(boolean equal) { _setRangeEqual("id", equal); } public void idIn(Integer in) { _setIn("id", String.valueOf(in)); } public void idNotIn(Integer notin) { _setNotIn("id", String.valueOf(notin)); } public void idOr(Integer or) { _setOr("id", String.valueOf(or)); } public void idOrIn(Integer in) { _setOrIn("id", String.valueOf(in)); } public void idOrNotIn(Integer notin) { _setOrNotIn("id", String.valueOf(notin)); } public void idNull() { _setNull("id", null); } public void idNotNull(Integer nl) { _setNotNull("id", String.valueOf(nl)); } public String getRoleName() { return this.roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public void roleNameDesc() { _setOrder("roleName", "DESC"); } public void roleNameAsc() { _setOrder("roleName", "ASC"); } public void roleNameMax(String max) { _setRangeMax("roleName", max); } public void roleNameMin(String min) { _setRangeMin("roleName", min); } public void roleNameEqual(boolean equal) { _setRangeEqual("roleName", equal); } public void roleNameLike(String like) { _setLike("roleName", like); setRoleName(null); } public void roleNameOrLike(String like) { _setOrLike("roleName", like); setRoleName(null); } public void roleNameIn(String in) { _setIn("roleName", in); } public void roleNameNotIn(String notin) { _setNotIn("roleName", notin); } public void roleNameOr(String or) { _setOr("roleName", or); } public void roleNameOrIn(String in) { _setOrIn("roleName", in); } public void roleNameOrNotIn(String notin) { _setOrNotIn("roleName", notin); } public void roleNameNull() { _setNull("roleName", null); } public void roleNameNotNull(String nl) { _setNotNull("roleName", nl); } public String getRoleMark() { return this.roleMark; } public void setRoleMark(String roleMark) { this.roleMark = roleMark; } public void roleMarkDesc() { _setOrder("roleMark", "DESC"); } public void roleMarkAsc() { _setOrder("roleMark", "ASC"); } public void roleMarkMax(String max) { _setRangeMax("roleMark", max); } public void roleMarkMin(String min) { _setRangeMin("roleMark", min); } public void roleMarkEqual(boolean equal) { _setRangeEqual("roleMark", equal); } public void roleMarkLike(String like) { _setLike("roleMark", like); setRoleMark(null); } public void roleMarkOrLike(String like) { _setOrLike("roleMark", like); setRoleMark(null); } public void roleMarkIn(String in) { _setIn("roleMark", in); } public void roleMarkNotIn(String notin) { _setNotIn("roleMark", notin); } public void roleMarkOr(String or) { _setOr("roleMark", or); } public void roleMarkOrIn(String in) { _setOrIn("roleMark", in); } public void roleMarkOrNotIn(String notin) { _setOrNotIn("roleMark", notin); } public void roleMarkNull() { _setNull("roleMark", null); } public void roleMarkNotNull(String nl) { _setNotNull("roleMark", nl); } public Integer getCreaterId() { return this.createrId; } public void setCreaterId(Integer createrId) { this.createrId = createrId; } public void createrIdDesc() { _setOrder("createrId", "DESC"); } public void createrIdAsc() { _setOrder("createrId", "ASC"); } public void createrIdMax(Integer max) { _setRangeMax("createrId", String.valueOf(max)); } public void createrIdMin(Integer min) { _setRangeMin("createrId", String.valueOf(min)); } public void createrIdEqual(boolean equal) { _setRangeEqual("createrId", equal); } public void createrIdIn(Integer in) { _setIn("createrId", String.valueOf(in)); } public void createrIdNotIn(Integer notin) { _setNotIn("createrId", String.valueOf(notin)); } public void createrIdOr(Integer or) { _setOr("createrId", String.valueOf(or)); } public void createrIdOrIn(Integer in) { _setOrIn("createrId", String.valueOf(in)); } public void createrIdOrNotIn(Integer notin) { _setOrNotIn("createrId", String.valueOf(notin)); } public void createrIdNull() { _setNull("createrId", null); } public void createrIdNotNull(Integer nl) { _setNotNull("createrId", String.valueOf(nl)); } public String getUpdatedAt() { return this.updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } public void updatedAtDesc() { _setOrder("updatedAt", "DESC"); } public void updatedAtAsc() { _setOrder("updatedAt", "ASC"); } public void updatedAtMax(String max) { _setRangeMax("updatedAt", max); } public void updatedAtMin(String min) { _setRangeMin("updatedAt", min); } public void updatedAtEqual(boolean equal) { _setRangeEqual("updatedAt", equal); } public void updatedAtLike(String like) { _setLike("updatedAt", like); setUpdatedAt(null); } public void updatedAtOrLike(String like) { _setOrLike("updatedAt", like); setUpdatedAt(null); } public void updatedAtIn(String in) { _setIn("updatedAt", in); } public void updatedAtNotIn(String notin) { _setNotIn("updatedAt", notin); } public void updatedAtOr(String or) { _setOr("updatedAt", or); } public void updatedAtOrIn(String in) { _setOrIn("updatedAt", in); } public void updatedAtOrNotIn(String notin) { _setOrNotIn("updatedAt", notin); } public void updatedAtNull() { _setNull("updatedAt", null); } public void updatedAtNotNull(String nl) { _setNotNull("updatedAt", nl); } public String getCreatedAt() { return this.createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public void createdAtDesc() { _setOrder("createdAt", "DESC"); } public void createdAtAsc() { _setOrder("createdAt", "ASC"); } public void createdAtMax(String max) { _setRangeMax("createdAt", max); } public void createdAtMin(String min) { _setRangeMin("createdAt", min); } public void createdAtEqual(boolean equal) { _setRangeEqual("createdAt", equal); } public void createdAtLike(String like) { _setLike("createdAt", like); setCreatedAt(null); } public void createdAtOrLike(String like) { _setOrLike("createdAt", like); setCreatedAt(null); } public void createdAtIn(String in) { _setIn("createdAt", in); } public void createdAtNotIn(String notin) { _setNotIn("createdAt", notin); } public void createdAtOr(String or) { _setOr("createdAt", or); } public void createdAtOrIn(String in) { _setOrIn("createdAt", in); } public void createdAtOrNotIn(String notin) { _setOrNotIn("createdAt", notin); } public void createdAtNull() { _setNull("createdAt", null); } public void createdAtNotNull(String nl) { _setNotNull("createdAt", nl); } public String getTimeStamp() { return this.timeStamp; } public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } public void timeStampDesc() { _setOrder("timeStamp", "DESC"); } public void timeStampAsc() { _setOrder("timeStamp", "ASC"); } public void timeStampMax(String max) { _setRangeMax("timeStamp", max); } public void timeStampMin(String min) { _setRangeMin("timeStamp", min); } public void timeStampEqual(boolean equal) { _setRangeEqual("timeStamp", equal); } public void timeStampLike(String like) { _setLike("timeStamp", like); setTimeStamp(null); } public void timeStampOrLike(String like) { _setOrLike("timeStamp", like); setTimeStamp(null); } public void timeStampIn(String in) { _setIn("timeStamp", in); } public void timeStampNotIn(String notin) { _setNotIn("timeStamp", notin); } public void timeStampOr(String or) { _setOr("timeStamp", or); } public void timeStampOrIn(String in) { _setOrIn("timeStamp", in); } public void timeStampOrNotIn(String notin) { _setOrNotIn("timeStamp", notin); } public void timeStampNull() { _setNull("timeStamp", null); } public void timeStampNotNull(String nl) { _setNotNull("timeStamp", nl); } public String _getPrimary() { return String.valueOf(id); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("{\n"); sb.append(" id:" + getId() + ",\n"); sb.append(" role_name:" + _getSnap(getRoleName()) + ",\n"); sb.append(" role_mark:" + _getSnap(getRoleMark()) + ",\n"); sb.append(" creater_id:" + getCreaterId() + ",\n"); sb.append(" updated_at:" + _getSnap(getUpdatedAt()) + ",\n"); sb.append(" created_at:" + _getSnap(getCreatedAt()) + ",\n"); sb.append(" time_stamp:" + _getSnap(getTimeStamp()) + "\n"); sb.append("}\n"); return sb.toString(); } public void setOrderBy(String sortName,String sortOrder){ if(sortOrder.equalsIgnoreCase("asc")){ if(sortName.equalsIgnoreCase("id")){ idAsc(); } if(sortName.equalsIgnoreCase("roleName")){ roleNameAsc(); } if(sortName.equalsIgnoreCase("roleMark")){ roleMarkAsc(); } if(sortName.equalsIgnoreCase("createrId")){ createrIdAsc(); } if(sortName.equalsIgnoreCase("updatedAt")){ updatedAtAsc(); } if(sortName.equalsIgnoreCase("createdAt")){ createdAtAsc(); } if(sortName.equalsIgnoreCase("timeStamp")){ timeStampAsc(); } } else if(sortOrder.equalsIgnoreCase("desc")){ if(sortName.equalsIgnoreCase("id")){ idDesc(); } if(sortName.equalsIgnoreCase("roleName")){ roleNameDesc(); } if(sortName.equalsIgnoreCase("roleMark")){ roleMarkDesc(); } if(sortName.equalsIgnoreCase("createrId")){ createrIdDesc(); } if(sortName.equalsIgnoreCase("updatedAt")){ updatedAtDesc(); } if(sortName.equalsIgnoreCase("createdAt")){ createdAtDesc(); } if(sortName.equalsIgnoreCase("timeStamp")){ timeStampDesc(); } } } public boolean equals(Object o) { if (o instanceof RoleInfo) { RoleInfo roleInfo = (RoleInfo) o; return roleInfo.getId().equals(getId()) && roleInfo.getRoleName().equals(getRoleName()) && roleInfo.getRoleMark().equals(getRoleMark()) && roleInfo.getCreaterId().equals(getCreaterId()) && roleInfo.getUpdatedAt().equals(getUpdatedAt()) && roleInfo.getCreatedAt().equals(getCreatedAt()) && roleInfo.getTimeStamp().equals(getTimeStamp()); } return false; } }
(6)业务数据层 IRoleInfoData.java
package com.hwabao.data; import java.util.List; import java.util.ArrayList; import com.hwabao.model.RoleInfo; import com.hwabao.common.Pager; /** * @author steven9801@163.com */ public interface IRoleInfoData { public int insertRoleInfo(RoleInfo roleInfo); public int updateRoleInfo(RoleInfo roleInfo); public int deleteRoleInfo(RoleInfo roleInfo); public RoleInfo getRoleInfo(RoleInfo roleInfo); public int getRoleInfoCount(RoleInfo roleInfo); public List<RoleInfo> selectRoleInfo(RoleInfo roleInfo); public List<RoleInfo> selectRoleInfo(RoleInfo roleInfo, Pager pager); public List<RoleInfo> selectRoleInfoByList(ArrayList<Integer> arrListId); public int getRoleInfoSearchCount(RoleInfo roleInfo); public List<RoleInfo> searchRoleInfo(RoleInfo roleInfo); public List<RoleInfo> searchRoleInfo(RoleInfo roleInfo, Pager pager); }
(7)业务服务层 RoleInfoService.java
package com.hwabao.service.impl; import java.util.List; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.hwabao.data.IRoleInfoData; import com.hwabao.model.RoleInfo; import com.hwabao.service.IRoleInfoService; import com.hwabao.common.Pager; /** * @author steven9801@163.com */ @Service public class RoleInfoService implements IRoleInfoService { @Autowired private IRoleInfoData roleInfoData; @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class }) public int insertRoleInfo(RoleInfo roleInfo) { return roleInfoData.insertRoleInfo(roleInfo); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class }) public int insertRoleInfoBatch(ArrayList<RoleInfo> arrListRoleInfo) { int insertedCount = 0; int result; RoleInfo roleInfo; for (int i = 0; i < arrListRoleInfo.size(); i++) { roleInfo = arrListRoleInfo.get(i); result = roleInfoData.insertRoleInfo(roleInfo); if (result < 1) { return 0; } insertedCount++; } return insertedCount; } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class }) public int updateRoleInfo(RoleInfo roleInfo) { return roleInfoData.updateRoleInfo(roleInfo); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class }) public int updateRoleInfoBatch(ArrayList<RoleInfo> arrListRoleInfo) { int updatedCount = 0; int result; RoleInfo roleInfo; for (int i = 0; i < arrListRoleInfo.size(); i++) { roleInfo = arrListRoleInfo.get(i); result = roleInfoData.updateRoleInfo(roleInfo); if (result < 1) { return 0; } updatedCount++; } return updatedCount; } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class }) public int deleteRoleInfo(RoleInfo roleInfo) { return roleInfoData.deleteRoleInfo(roleInfo); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class }) public int deleteRoleInfoBatch(ArrayList<RoleInfo> arrListRoleInfo) { int deletedCount = 0; int result; RoleInfo roleInfo; for (int i = 0; i < arrListRoleInfo.size(); i++) { roleInfo = arrListRoleInfo.get(i); result = roleInfoData.deleteRoleInfo(roleInfo); if (result < 1) { return 0; } deletedCount++; } return deletedCount; } @Override public RoleInfo getRoleInfo(RoleInfo roleInfo) { return roleInfoData.getRoleInfo(roleInfo); } @Override public RoleInfo getRoleInfo(Integer id) { RoleInfo roleInfo = new RoleInfo(); roleInfo.setId(id); return getRoleInfo(roleInfo); } @Override public int getRoleInfoCount(RoleInfo roleInfo) { return roleInfoData.getRoleInfoCount(roleInfo); } @Override public List<RoleInfo> selectRoleInfo(RoleInfo roleInfo) { return roleInfoData.selectRoleInfo(roleInfo); } @Override public List<RoleInfo> selectRoleInfo(RoleInfo roleInfo, Pager pager) { if (null != pager) { int count = roleInfoData.getRoleInfoCount(roleInfo); if (count == 0) { return null; } pager.setRowCount(count); } return roleInfoData.selectRoleInfo(roleInfo, pager); } @Override public List<RoleInfo> selectRoleInfoByList(ArrayList<Integer> arrListId) { if (arrListId.size() == 0) { return null; } return roleInfoData.selectRoleInfoByList(arrListId); } @Override public int getRoleInfoSearchCount(RoleInfo roleInfo) { return roleInfoData.getRoleInfoSearchCount(roleInfo); } @Override public List<RoleInfo> searchRoleInfo(RoleInfo roleInfo) { return roleInfoData.searchRoleInfo(roleInfo); } @Override public List<RoleInfo> searchRoleInfo(RoleInfo roleInfo, Pager pager) { if (null != pager) { int count = roleInfoData.getRoleInfoSearchCount(roleInfo); if (count == 0) { return null; } pager.setRowCount(count); } return roleInfoData.searchRoleInfo(roleInfo, pager); } }
package com.hwabao.service; import java.util.List; import java.util.ArrayList; import com.hwabao.model.RoleInfo; import com.hwabao.common.Pager; /** * @author steven9801@163.com */ public interface IRoleInfoService { public int insertRoleInfo(RoleInfo roleInfo); public int insertRoleInfoBatch(ArrayList<RoleInfo> arrListRoleInfo); public int updateRoleInfo(RoleInfo roleInfo); public int updateRoleInfoBatch(ArrayList<RoleInfo> arrListRoleInfo); public int deleteRoleInfo(RoleInfo roleInfo); public int deleteRoleInfoBatch(ArrayList<RoleInfo> arrListRoleInfo); public RoleInfo getRoleInfo(RoleInfo roleInfo); public RoleInfo getRoleInfo(Integer id); public int getRoleInfoCount(RoleInfo roleInfo); public List<RoleInfo> selectRoleInfo(RoleInfo roleInfo); public List<RoleInfo> selectRoleInfo(RoleInfo roleInfo, Pager pager); public List<RoleInfo> selectRoleInfoByList(ArrayList<Integer> arrListId); public int getRoleInfoSearchCount(RoleInfo roleInfo); public List<RoleInfo> searchRoleInfo(RoleInfo roleInfo); public List<RoleInfo> searchRoleInfo(RoleInfo roleInfo, Pager pager); }
就这样简单整个业务表的CRUD结构清晰的完整的呈现在你面前啦。管中窥豹,真正拥有者会如获至宝。
敬请期待下期:
asp.net mvc 实战化项目之三板斧
感兴趣的朋友扫下面的二维码给点打赏吧!