文档章节

spring mvc 实战化项目之三板斧

火腿骑士
 火腿骑士
发布于 2016/11/20 14:59
字数 4743
阅读 11
收藏 0
点赞 0
评论 0

laravel实战化项目之三板斧

spring mvc 实战化项目之三板斧

asp.net mvc 实战化项目之三板斧

接上文希望从一张表(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 实战化项目之三板斧

感兴趣的朋友扫下面的二维码给点打赏吧!

                  

虽功未成,亦未敢藏私,众侠诸神通尽录于此,竟成一笈,名葵花宝典,以飨后世。 
邮箱:steven9801@163.com 
QQ: 48039387

© 著作权归作者所有

共有 人打赏支持
火腿骑士
粉丝 0
博文 4
码字总数 14614
作品 0
嘉定
部门经理
asp.net mvc 实战化项目之三板斧

laravel实战化项目之三板斧 spring mvc 实战化项目之三板斧 asp.net mvc 实战化项目之三板斧 接上文希望从一张表(tbroleinfo 用户角色表)的CRUD展开asp.net mvc的项目实战化魅力。 开发技术...

火腿骑士 ⋅ 2016/11/20 ⋅ 0

三流程序员与一流程序员之间的区别,看看你是属于哪一类?

源码系列 手写spring mvc框架 基于Spring JDBC手写ORM框架 实现自己的MyBatis Spring AOP实战之源码分析 Spring IOC高级特性应用分析 ORM框架底层实现原理剖析 手写Spring MVC框架实现 手把手...

茶轴的青春 ⋅ 04/17 ⋅ 0

Spring+mybatis测试项目总结

1.项目目的 a.通过Spring+Mybatis实现通过web访问达成mySql的操作 b.理解Spring+Mybatis的配置 c.理解maven对项目的管理 2.配置文件 a.采用maven约定结构,src/main/java、src/main/resource...

飓风2000 ⋅ 2014/07/26 ⋅ 0

Java Web学习计划

--- 本月为入门阶段,从零开始,一步一步的做出一个实用的网站。 深入学习Java语言,初步掌握前端技术,使用JSP和MySQL完成一个简单的网站 第1周 Java高级编程学习目标:
1.深入了解JDK环境...

SVD ⋅ 2016/12/01 ⋅ 0

从SpringBoot到SpringMVC

概述 用久了SpringBoot,深受其约定大于配置的便利性毒害之后,我想回归到SpringMVC时代,看看SpringMVC开发模式中用户是如何参与的。本文就来体验一下SpringMVC时代开发的流程。 SpringMVC架...

CodeSheep ⋅ 06/11 ⋅ 0

Java开发者不会这些永远都只能是三流程序员,细数一下你是不是?

源码系列 手写spring mvc框架 基于Spring JDBC手写ORM框架 实现自己的MyBatis Spring AOP实战之源码分析 Spring IOC高级特性应用分析 ORM框架底层实现原理剖析 手写Spring MVC框架实现 手把手...

美的让人心动 ⋅ 04/16 ⋅ 0

搭建Spring + SpringMVC + Mybatis框架之三(整合Spring、Mybatis和Spring MVC)

目录 整合Spring和SpringMVC 整合Spring和SpringMVC 之前已经整合了spring和mybatis,现在在此基础上整合SSM。 项目目录: 思路:SpringMVC的配置文件独立,然后在web.xml中配置整合。 (1)...

张辉原 ⋅ 2017/06/15 ⋅ 0

书单丨5本Java后端技术书指引你快速进阶

一名Java开发工程师 不仅要对Java语言及特性有深层次的理解 而且需要掌握与Java相关的 框架、生态及后端开发知识 本文涉及多种后端开发需要掌握的技能 对于帮助提高开发能力非常有帮助 NO.1...

Java高级架构 ⋅ 05/30 ⋅ 0

ZHENFENGSHISAN/perfect-ssm

Quick Start 项目简介 ssm系列 ssm-demo:Spring+SpringMVC+Mybatis+easyUI整合 perfect-ssm:RESTful API+redis缓存 ssm-cluster:前后端分离+集群部署 ssm-dubbo:dubbo服务化 ssm-micro-se......

ZHENFENGSHISAN ⋅ 2017/09/18 ⋅ 0

解决js处理Long类型丢失精度的问题

项目中很多时候都会用到json,常用的有fastjson,Jackson等等这些,有时候为了统一,我们通常就会约定使用某一种。 不管使用哪种,Spring MVC返回个前段Long类型的数据时,js在获取数据时会丢...

xiaomin0322 ⋅ 05/30 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

SAS笔记-宏2

宏是一种文本,一般来说其编译是在程序执行之前。 宏变量的创建 %let语句 %let macro_variables = text; %let是常见的宏变量建立方式,其编译就在执行前。如下例中,想要宏变量test等于数据集...

tonorth123 ⋅ 10分钟前 ⋅ 0

如何使用serverchan微信推送告警

之前实现推送告警信息到微信的方法有如下几种: 1、通过企业公众号实现----收费: 2、通过QQ邮箱,在微信平台上开启收到邮件进行提醒; 3、第三方告警平台API,一般也是收费的; 不过最近看文...

问题终结者 ⋅ 37分钟前 ⋅ 0

TCP的RPC

RPC就是远程方法调用(Remote Process Call ),包含了客户端和服务端,涉及了对象的序列化传输。 1.服务端启动,注册远程调用的类2.客户端发送请求信息包含类、方法、参数的一些信息、序列化传...

Cobbage ⋅ 58分钟前 ⋅ 0

IOS-UI UI初步代码布局添加事件

ISO开发界面,UI是必须学习的一部分,其实很早之前想学来了,一直没有沉下心来学习。看到IOS的代码风格和布局就别扭的不行,跟java代码和android布局比较显得不是那么方便,所以一直到现在。...

京一 ⋅ 今天 ⋅ 0

浅谈OpenDaylight的二次开发

OpenDaylight作为一款开源SDN网络控制器,依托于强大的社区支持以及功能特性,成为了目前主流的SDN网络控制器开发平台。在比较稳定的OpenDaylight Helium版本中,已经为开发者提供了大量的网...

wangxuwei ⋅ 今天 ⋅ 0

API 开发中可选择传递 token 接口遇到的一个坑

在做 API 开发时,不可避免会涉及到登录验证,我使用的是jwt-auth 在登录中会经常遇到一个token过期的问题,在config/jwt.php默认设置中,这个过期时间是一个小时,不过为了安全也可以设置更...

等月人 ⋅ 今天 ⋅ 0

Java NIO之文件处理

程序要操作本地操作系统的一个文件,可以分为以下三个部分: 对文件位置的操作 对文件的操作 对文件内容的操作 其中,对文件内容的操作在 Java NIO之Channel 中已经有了介绍,通过FileChann...

士别三日 ⋅ 今天 ⋅ 0

Maven的pom.xml配置文件详解

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.......

小海bug ⋅ 今天 ⋅ 0

解决httpclient超时设置不生效的问题

最近公司有项目需要通过http调用第三方服务,且第三方服务偶有超时,故需要设置一定的超时时间防止不响应的情况出现。 初始设置如下: [java] view plain copy //超时设置 RequestConfig re...

Mr_Tea伯奕 ⋅ 今天 ⋅ 0

过滤器Filter和拦截器HandlerInterceptor

过滤器 依赖于servlet容器。在实现上基于函数回调,可以对几乎所有请求进行过滤,但是缺点是一个过滤器实例只能在容器初始化时调用一次。使用过滤器的目的是用来做一些过滤操作,获取我们想要...

hutaishi ⋅ 今天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部