在包“com.example.demo.model”中新建一个“Permission”类(如果自己添加model类时,只须定义好属性,然后利用eclipse的生成getter和setter功能,直接生成代码),代码如下:
package com.example.demo.model;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
@TableName("t_sys_permission")//数据库对应表名
public class Permission {
@TableId
private String id;//@TableId表示主键,与字段名称大小写一致
private String name;//与字段名称大小写一致
private String descripion;//与字段名称大小写一致
private String url;//与字段名称大小写一致
private String pid;//与字段名称大小写一致
private String perms;//与字段名称大小写一致
private Integer type;//与字段名称大小写一致
private String icon;//与字段名称大小写一致
private Integer order_num;//与字段名称大小写一致
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescripion() {
return descripion;
}
public void setDescripion(String descripion) {
this.descripion = descripion;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPerms() {
return perms;
}
public void setPerms(String perms) {
this.perms = perms;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Integer getOrder_num() {
return order_num;
}
public void setOrder_num(Integer order_num) {
this.order_num = order_num;
}
}
在包“com.example.demo.model”中再新建一个“RolePermission”类(用来操作关联表),代码如下:
package com.example.demo.model;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
@TableName("t_sys_permission_role")//数据库对应表名,关联表
public class RolePermission {
@TableId
private String id;//@TableId表示主键,与字段名称大小写一致
private String sys_role_id;//与字段名称大小写一致
private String sys_permission_id;//与字段名称大小写一致
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSys_role_id() {
return sys_role_id;
}
public void setSys_role_id(String sys_role_id) {
this.sys_role_id = sys_role_id;
}
public String getSys_permission_id() {
return sys_permission_id;
}
public void setSys_permission_id(String sys_permission_id) {
this.sys_permission_id = sys_permission_id;
}
}
在包“com.example.demo.model”中再新建一个“Role”类(因为需要用到角色,所以角色model先创建好),代码如下:
package com.example.demo.model;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
@TableName("t_sys_role")//数据库对应表名
public class Role {
@TableId
private String id;//@TableId表示主键,与字段名称大小写一致
private String name;//与字段名称大小写一致
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
-
-
- 权限vo类
-
在包“com.example.demo.vo”中新建一个“PermissionVO”类(如果自己添加类时,只须定义好属性,然后利用eclipse的生成getter和setter功能,直接生成代码),代码如下:
package com.example.demo.vo;
public class PermissionVO{
private String id;
private String name;
private String descripion;
private String url;
private String pid;
private String perms;
private Integer type;
private String icon;
private Integer order_num;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescripion() {
return descripion;
}
public void setDescripion(String descripion) {
this.descripion = descripion;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPerms() {
return perms;
}
public void setPerms(String perms) {
this.perms = perms;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Integer getOrder_num() {
return order_num;
}
public void setOrder_num(Integer order_num) {
this.order_num = order_num;
}
}
-
-
- 权限mapper类以及xml文件
-
在包“com.example.demo.mapper”中新建一个“PermissionMapper”接口,代码如下:
package com.example.demo.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.example.demo.model.Permission;
import com.example.demo.vo.PermissionVO;
@Mapper
public interface PermissionMapper extends BaseMapper<Permission>{
List<PermissionVO> selectPermissionListPage(Pagination page ,PermissionVO permissionVO);
List<PermissionVO> selectUserPermissionList(String userid);
}
在“src/main/resources”中的“mapper”文件夹中,新建一个文件,命名为“PermissionMapper.xml”,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 指明当前xml对应的Mapper -->
<mapper namespace="com.example.demo.mapper.PermissionMapper">
<!-- 多表查询,Select 的as后面的名称必须与UserVO属性名大小写一致 -->
<select id="selectPermissionListPage" parameterType="com.example.demo.vo.PermissionVO" resultType="com.example.demo.vo.PermissionVO">
SELECT
p.id as id,
p.name as name,
p.descripion as descripion,
p.url as url,
p.pid as pid,
p.perms as perms,
p.type as type,
p.icon as icon,
p.order_num as order_num
FROM
t_sys_permission p
WHERE 1=1
<if test="name != null">
and p.name like concat('%',#{name},'%')
</if>
<if test="url != null">
and p.url like concat('%',#{url},'%')
</if>
</select>
<select id="selectUserPermissionList" parameterType="String" resultType="com.example.demo.vo.PermissionVO">
SELECT
pr.sys_permission_id as id
FROM
t_sys_user u
INNER JOIN t_sys_role_user ru ON u.id = ru.sys_user_id
INNER JOIN t_sys_permission_role pr ON ru.sys_role_id = pr.sys_role_id
WHERE
u.id = #{userid}
</select>
</mapper>
这里的xml文件除了扩展分页查询,还扩展了一个连接查询,查询出用户拥有的全部权限(菜单)。
在包“com.example.demo.mapper”中再新建一个“RolePermissionMapper”接口,代码如下:
package com.example.demo.mapper;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.example.demo.model.RolePermission;
@Mapper
public interface RolePermissionMapper extends BaseMapper<RolePermission>{
}
该接口只继承了通用mapper,不做扩展。
在包“com.example.demo.service”中新建一个“PermissionService”类,代码如下:
package com.example.demo.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.example.demo.mapper.PermissionMapper;
import com.example.demo.mapper.RolePermissionMapper;
import com.example.demo.model.Permission;
import com.example.demo.model.Role;
import com.example.demo.model.RolePermission;
import com.example.demo.util.Convert;
import com.example.demo.util.SnowflakeIdWorker;
import com.example.demo.vo.DataTableResult;
import com.example.demo.vo.Menu;
import com.example.demo.vo.MenuList;
import com.example.demo.vo.PermissionVO;
@Service
public class PermissionService {
@Autowired
private PermissionMapper permissionMapper;// 注入mapper进行数据操作
@Autowired
private RolePermissionMapper rolePermissionMapper;// 注入mapper进行数据操作
// 对于执行数据修改的方法加上事务处理
@Transactional
public int delete(String ids) {
// ids,逗号隔开的主键
List<String> listid = Convert.toListStrArray(ids);
return permissionMapper.deleteBatchIds(listid);
}
public Permission selectById(String id) {
// permissionMapper.selectOne(permission),selectOne可以按照其他字段来查询一条记录
return permissionMapper.selectById(id);
}
// 对于执行数据修改的方法加上事务处理
@Transactional
public int updateById(Permission permission) {
return permissionMapper.updateById(permission);
}
// 对于执行数据修改的方法加上事务处理
@Transactional
public int insert(Permission permission) {
// 添加雪花主键id
permission.setId(SnowflakeIdWorker.getUUID());
int n = permissionMapper.insert(permission);
// n=1/0; //事务测试
return n;
}
/**
* 采用集成的查询方法
*
* @param username
* @return
*/
public List<Permission> selectList() {
EntityWrapper<Permission> wrapper = new EntityWrapper<Permission>();
// wrapper.like("username", username);
return permissionMapper.selectList(wrapper);
}
/**
* 返回角色所有权限
*
* @param role
* @return
*/
public List<RolePermission> selectRolePermission(Role role) {
EntityWrapper<RolePermission> wrapper = new EntityWrapper<RolePermission>();
wrapper.eq("sys_role_id", role.getId());// 可以多个条件
return rolePermissionMapper.selectList(wrapper);
}
// 对于执行数据修改的方法加上事务处理
@Transactional
public void author(Role role, String ids) {
// 1.清除原有分配
EntityWrapper<RolePermission> wrapper = new EntityWrapper<RolePermission>();
wrapper.eq("sys_role_id", role.getId());// 可以多个条件
rolePermissionMapper.delete(wrapper);
// 2.重新插入权限
if (!StringUtils.isEmpty(ids)) {
List<String> listrid = Convert.toListStrArray(ids);
SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
for (String pid : listrid) {
RolePermission rp = new RolePermission();
rp.setId(String.valueOf(idWorker.nextId()));
rp.setSys_role_id(role.getId());
rp.setSys_permission_id(pid);
rolePermissionMapper.insert(rp);
}
}
}
/**
* 分页查询
*
* @param permission
* @return
*/
public DataTableResult selectPermissionListPage(PermissionVO permissionVO, int start, int length, String orderField,
String orderDir) {
Page<PermissionVO> page = null;
// 排序
if (!StringUtils.isEmpty(orderDir) && !StringUtils.isEmpty(orderField)) {
if (orderDir.equals("asc")) {
page = new Page<>(start / length + 1, length, orderField, true);// 当前页,每页总条数 构造 page 对象
} else {
page = new Page<>(start / length + 1, length, orderField, false);// 当前页,每页总条数 构造 page 对象
}
} else {
page = new Page<>(start / length + 1, length, "id", false);// 默认id降序
}
page.setRecords(permissionMapper.selectPermissionListPage(page, permissionVO));
DataTableResult result = new DataTableResult();
result.setRecordsTotal(page.getTotal());
result.setRecordsFiltered(page.getTotal());
result.setData(page.getRecords());
return result;
}
public List<Permission> getRootMenu() {
EntityWrapper<Permission> wrapper = new EntityWrapper<Permission>();
wrapper.eq("pid", 0);
return permissionMapper.selectList(wrapper);
}
public List<Permission> getSubMenu(String pid) {
EntityWrapper<Permission> wrapper = new EntityWrapper<Permission>();
wrapper.eq("pid", pid);
return permissionMapper.selectList(wrapper);
}
public List<MenuList> getUserMenu(String userid){
List<MenuList> menulist = new ArrayList<MenuList>();
//1.查询用户的菜单id
List<PermissionVO> userPermissionList = permissionMapper.selectUserPermissionList(userid);
//2.构造菜单结构
List<Permission> rootMenuList = getRootMenu();
for(Permission p:rootMenuList) {
//判断是否有权限
boolean flag = false;
for(PermissionVO pv:userPermissionList) {
if(pv.getId().equals(p.getId())) {
flag = true;
break;
}
}
if(flag) {
//构造菜单
Menu menu=new Menu();
menu.setMenuIcon(p.getIcon());
menu.setMenuText(p.getName());
menu.setMenuUrl(p.getUrl());
//有权限,获取下级菜单
List<Permission> subMenuList = getSubMenu(p.getId());
List<Menu> menulistsub = new ArrayList<Menu>();//构造下级菜单
for(Permission p2:subMenuList) {
//判断是否有权限
boolean flag2 = false;
for(PermissionVO pv2:userPermissionList) {
if(pv2.getId().equals(p2.getId())) {
flag2 = true;
break;
}
}
if(flag2) {
//有权限
//构造二级菜单
Menu menu2=new Menu();
menu2.setMenuIcon(p2.getIcon());
menu2.setMenuText(p2.getName());
menu2.setMenuUrl(p2.getUrl());
menulistsub.add(menu2);
}
}
MenuList mList =new MenuList();
mList.setMenu(menu);
mList.setSubmenus(menulistsub);
menulist.add(mList);
}
}
return menulist;
}
}
这个service是比较复杂的,除了基本的增删改查和分页查询之外,还扩展了角色的授权和菜单的构造,这两部分有点难,注意理解代码。
在包“com.example.demo.controller”中新建一个“PermissionController”类,代码如下:
package com.example.demo.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.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.demo.model.Permission;
import com.example.demo.model.Role;
import com.example.demo.model.RolePermission;
import com.example.demo.service.PermissionService;
import com.example.demo.vo.DataTableResult;
import com.example.demo.vo.Json;
import com.example.demo.vo.PermissionVO;
import com.example.demo.vo.ZTreeNode;
@Controller
@RequestMapping("/PermissionController")
public class PermissionController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private String prefix = "admin/permission";// 页面的路径
@Autowired
private PermissionService permissionService;// 注入业务层的service
// 未加入@ResponseBody用来返回数据给页面
@RequestMapping("view")
public String view(Model model) {
return prefix + "/view";
}
// @ResponseBody,直接通过js异步返回数据给页面
@RequestMapping("list")
@ResponseBody
public DataTableResult list(HttpServletRequest request, PermissionVO permissionVO) {
// DataTableResult返回给datatables控件的数据格式
DataTableResult result = new DataTableResult();
// 获取分页参数
int start = Integer.parseInt(request.getParameter("start"));
int length = Integer.parseInt(request.getParameter("length"));
// 获取排序字段
String orderIdx = request.getParameter("order[0][column]");
// 获取排序字段名
String orderField = request.getParameter("columns[" + orderIdx + "][name]");
// 获取排序方式,降序desc或者升序asc
String orderDir = request.getParameter("order[0][dir]");
result = permissionService.selectPermissionListPage(permissionVO, start, length, orderField, orderDir);
// result.setDraw(permissionVO.getDraw());
return result;
}
// @ResponseBody,直接通过js异步返回数据给页面
@RequestMapping("insert")
@ResponseBody
public Json insert(Permission permission) {
Json j = new Json();
if (permissionService.insert(permission) > 0) {
j.setSuccess(true);
j.setMsg("添加成功!");
} else {
j.setSuccess(false);
j.setMsg("添加失败!");
}
return j;
}
// @ResponseBody,直接通过js异步返回数据给页面
@RequestMapping("update")
@ResponseBody
public Json updateById(Permission permission) {
Json j = new Json();
if (permissionService.updateById(permission) > 0) {
j.setSuccess(true);
j.setMsg("修改成功!");
} else {
j.setSuccess(false);
j.setMsg("修改失败!");
}
return j;
}
// @ResponseBody,直接通过js异步返回数据给页面
@RequestMapping("select")
@ResponseBody
public Json selectById(Permission permission) {
Json j = new Json();
j.setSuccess(true);
j.setObj(permissionService.selectById(permission.getId()));
return j;
}
// @ResponseBody,直接通过js异步返回数据给页面
@RequestMapping("delete")
@ResponseBody
public Json delete(HttpServletRequest request) {
Json j = new Json();
String ids = request.getParameter("ids");
if (!StringUtils.isEmpty(ids)) {
j.setSuccess(true);
j.setObj("成功删除" + permissionService.delete(ids) + "条记录");
} else {
j.setSuccess(false);
j.setMsg("没有需要删除的记录!");
}
return j;
}
/**
* 获取树形结构
**/
@RequestMapping("tree")
@ResponseBody
public List<ZTreeNode> getTreeList(HttpServletRequest request, Role role) {
List<Permission> permissionList = permissionService.selectList();
List<RolePermission> rolePermissionsList = permissionService.selectRolePermission(role);
List<ZTreeNode> list = new ArrayList<ZTreeNode>();
for (Permission p : permissionList) {
ZTreeNode zt = new ZTreeNode();
zt.setId(p.getId());
zt.setName(p.getName());
zt.setOpen(true);
zt.setpId(p.getPid());
if (p.getPid().equals("0"))
zt.setIsParent(true);
else
zt.setIsParent(false);
zt.setMsg(p.getDescripion() + "");
// 查询是否已经分配了权限,有的打勾
for (RolePermission rp : rolePermissionsList) {
if (rp.getSys_permission_id().equals(p.getId())) {
zt.setChecked(true);
break;
}
}
list.add(zt);
}
return list;
}
// @ResponseBody,直接通过js异步返回数据给页面
@RequestMapping("author")
@ResponseBody
public Json author(HttpServletRequest request, Role role) {
Json j = new Json();
String ids = request.getParameter("ids");
if (!StringUtils.isEmpty(role.getId())) {
permissionService.author(role, ids);
j.setSuccess(true);
j.setObj("分配权限成功!");
} else {
j.setSuccess(false);
j.setMsg("角色id为空!");
}
return j;
}
}
这个controller用到了树形结构数据ZTreeNode,把数据组装成树形结构需要的格式返回给前端,author方法利用前端树形结构返回的选中id值(以逗号隔开进行拼接)进行角色的权限分配。
添加权限管理界面,在“admin”文件夹中新建一个文件夹“permission”,在“permission”文件夹-> 右键->new->file,输入“view.html”(这里的路径主要是由controller的转发方法决定,保持一致即可),代码如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="renderer" content="webkit">
<title>权限管理</title>
<meta name="keywords" content="">
<meta name="description" content="">
<!--[if lt IE 9]>
<meta http-equiv="refresh" content="0;ie.html" />
<![endif]-->
<link rel="shortcut icon" href="favicon.ico">
<link th:href="@{/static/css/bootstrap.min.css?v=3.3.6}"
rel="stylesheet">
<link th:href="@{/static/css/font-awesome.min.css?v=4.4.0}"
rel="stylesheet">
<link th:href="@{/static/css/animate.css}" rel="stylesheet">
<link th:href="@{/static/css/style.css?v=4.1.0}" rel="stylesheet">
<!-- Data Tables -->
<link
th:href="@{/static/css/plugins/dataTables/dataTables.bootstrap.css}"
rel="stylesheet">
<!-- toastr -->
<link th:href="@{/static/css/plugins/toastr/toastr.min.css}" rel="stylesheet">
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row">
<div class="col-sm-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>权限管理</h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="dropdown-toggle" data-toggle="dropdown" href="table_data_tables.html#">
<i class="fa fa-wrench"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="table_data_tables.html#">选项1</a>
</li>
<li><a href="table_data_tables.html#">选项2</a>
</li>
</ul>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
</div>
</div>
<div class="ibox-content">
<div class="form-horizontal">
<div class="form-group">
<div class="col-sm-4">
<button id="btn_add" class="btn btn-primary btn-sm" ><i class="fa fa-plus"></i> 添加</button>
<button id="btn_del" class="btn btn-danger btn-sm m-l-sm" ><i class="fa fa-remove"></i> 删除</button>
<button id="btn_export" class="btn btn-primary btn-sm m-l-sm" onclick="$('#table').tableExport({type:'excel',escape:'false',tableName:'导出表格',ignoreColumn:[0]});"><i class="fa fa-file-excel-o"></i> 导出</button>
</div>
<label class="col-sm-1 control-label">搜索:</label>
<div class="col-sm-2">
<select id="searchfield" class="form-control">
<!-- value为查找字段名称 -->
<option value="name">名称</option>
<option value="url">URL</option>
</select>
</div>
<div class="col-sm-3">
<input id="keyword" type="search" class="form-control" placeholder="关键字" />
</div>
<div class="col-sm-2">
<button id="btn_search" class="btn btn-primary btn-sm m-l-sm" ><i class="fa fa-search"></i> 搜索</button>
</div>
</div>
</div>
<table class="table table-striped table-bordered table-hover" id="table">
<thead>
<tr>
<th style="padding-left: 10px;">
<input type="checkbox" id="cb_selectAll" class="input-lg" style="width:20px;height:20px;"/>
</th>
<th>id</th>
<th>name</th>
<th>url</th>
<th>pid</th>
<th>icon</th>
<th>order_num</th>
<th>操作</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- 模态窗口 -->
<div class="modal fade" data-backdrop="static" id="modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h2 class="modal-title" id="modaltitle"></h2>
</div>
<div class="modal-body">
<div class="row">
<!-- 表单布局 -->
<form id="form">
<div class="col-md-12">
<div class="form-group">
<label class="col-sm-3 control-label"><font color="#FF0000">*</font>权限名称:</label>
<div class="col-sm-9">
<!-- 保存修改的主键值 -->
<input type="hidden" name="id" id="id">
<input class="form-control" type="text" name="name" id="name"
placeholder="请输入权限名称" >
<span class="help-block m-b-none"></span>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="col-sm-3 control-label">url:</label>
<div class="col-sm-9">
<input class="form-control" type="text" name="url" id="url"
placeholder="请输入url" >
<span class="help-block m-b-none"></span>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="col-sm-3 control-label"><font color="#FF0000">*</font>pid(0为根节点):</label>
<div class="col-sm-9">
<input class="form-control" type="text" name="pid" id="pid"
placeholder="请输入pid" >
<span class="help-block m-b-none"></span>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="col-sm-3 control-label">icon:</label>
<div class="col-sm-9">
<input class="form-control" type="text" name="icon" id="icon"
placeholder="请输入icon" >
<span class="help-block m-b-none"></span>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="col-sm-3 control-label">order_num:</label>
<div class="col-sm-9">
<input class="form-control" type="number" name="order_num" id="order_num"
placeholder="请输入order_num" >
<span class="help-block m-b-none"></span>
</div>
</div>
</div>
</form>
<!-- 表单布局结束 -->
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white"
data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" id="btn_save">保存</button>
</div>
</div>
</div>
</div>
<!-- 模态窗口结束 -->
<!-- 全局js -->
<script th:src="@{/static/js/jquery.min.js?v=2.1.4}"></script>
<script th:src="@{/static/js/bootstrap.min.js?v=3.3.6}"></script>
<script th:src="@{/static/js/plugins/layer/layer.min.js}"></script>
<!-- 自定义js -->
<script th:src="@{/static/js/content.js}"></script>
<!-- Data Tables -->
<script th:src="@{/static/js/plugins/dataTables/jquery.dataTables.js}"></script>
<script
th:src="@{/static/js/plugins/dataTables/dataTables.bootstrap.js}"></script>
<!-- tableexport -->
<!-- 前端直接导出excel有一定的缺陷,使用后台导出功能更强大
后台导出:阿里巴巴项目组提供了easyexcel工具类,github地址:https://github.com/alibaba/easyexcel -->
<script th:src="@{/static/js/plugins/tableexport/tableExport.js}"></script>
<script th:src="@{/static/js/plugins/tableexport/jquery.base64.js}"></script>
<!-- Toastr script -->
<script th:src="@{/static/js/plugins/toastr/toastr.min.js}"></script>
<!-- jQuery Validation plugin javascript-->
<script th:src="@{/static/js/plugins/validate/jquery.validate.min.js}"></script>
<script th:src="@{/static/js/plugins/validate/messages_zh.min.js}"></script>
<!-- Page-Level Scripts -->
<script>
//表格行中的按钮点击事件
function edit(id){
//异步获取数据
$.ajax({
type: "get",
data: {
id:id,//第一个id为参数名,第二个为参数值
},
url: "/PermissionController/select",//后台处理地址
success: function (data) {
//console.log(data);
if(data.success){
//设置数据
$("#id").val(data.obj.id);//修改数据必须有主键值
$("#name").val(data.obj.name);
$("#url").val(data.obj.url);
$("#pid").val(data.obj.pid);
$("#icon").val(data.obj.icon);
$("#order_num").val(data.obj.order_num);
$("#modaltitle").text("修改权限");
$("#modal").modal("show");
}else{
toastr.error(data.msg, '错误!');
}
}
}); // end ajax
}//end edit
$(document).ready(function () {
var datatable= $('#table').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: "/PermissionController/list",
type:"post",
data: function (d) {
//把字段名和关键词发送给controller进行查询,自动映射到vo模型的相应属性中
d[$('#searchfield').val()]=$('#keyword').val()
}
},
"language": {
"lengthMenu": "每页 _MENU_ 行",
"info": "从 _START_ 到 _END_,共 _TOTAL_ 记录",
"zeroRecords": "没有找到记录",
"infoEmpty": "暂无记录",
"infoFiltered": "(从 _MAX_ 条记录过滤)",
"paginate": {
"previous": "上一页",
"next": "下一页",
},
"processing": "正在加载..."
},
"autoWidth": false,
"pageLength": 5,
"lengthChange": false,
"searching": false,
"columns": [
{"data":"id","orderable": false,
"render": function ( data, type, full, meta ) {
return '<input type="checkbox" value="'+data+'" class="input-lg" style="width:20px;height:20px;" />';
}
},
{"data":"id","name":"id"},
{"data":"name","name":"name"},
{"data":"url","name":"url"},
{"data":"pid","name":"pid"},
{"data":"icon","name":"icon"},
{"data":"order_num","name":"order_num"},
//有排序功能必须指定name为字段名称
{"data":"id","orderable": false,
"render": function ( data, type, full, meta ) {
return '<button id="btn_edit" class="btn btn-primary btn-sm" οnclick="edit(\''+data+'\')"><i class="fa fa-edit"></i> 查看修改</button>';
}
},
],
"order": [
[1, 'desc']
]//默认排序
});
$("#btn_search").click(function(){
datatable.ajax.reload();//根据关键词重新加载数据
});
//全选
$("#cb_selectAll").click(function(){
if ($("#cb_selectAll").get(0).checked) {
$("#table tbody :checkbox").prop("checked", true);
}else{
$("#table tbody :checkbox").prop("checked", false);
}
});
//toastr选项
toastr.options = {
"positionClass": "toast-bottom-center",
}
//删除
$("#btn_del").click(function(){
//获取选中的复选框
var checkboxlist=$("#table tbody :checked");
if(checkboxlist.length>0){
if(!confirm("您确定删除数据吗?"))
{
return;
}
}else{
toastr.error("请选择要删除的记录。", '错误!');
return;
}
var ids="";
$.each(checkboxlist, function(n, cb) {
ids+=cb.value+",";
});
if(ids.length>0){
ids=ids.substring(0,ids.length-1);
}
//异步删除数据
$.ajax({
type: "post",
data: {
ids:ids,//第一个ids为参数名,第二个为参数值
},
url: "/PermissionController/delete",//后台处理地址
success: function (data) {
if(data.success){
toastr.success(data.msg, '删除成功!');
datatable.ajax.reload(null, false);//刷新当前页
}else{
toastr.error(data.msg, '错误!');
}
}
});
});//end btn_del
$("#btn_add").click(function(){
//清空数据
$("#name").val("");
$("#url").val("");
$("#pid").val("");
$("#icon").val("");
$("#order_num").val("");
//validator.resetForm();//重置验证
$("#modaltitle").text("添加权限");
$("#modal").modal("show");
});//end add
//不用改,以下为修改jQuery Validation插件兼容Bootstrap的方法,没有直接写在插件中是为了便于插件升级
$.validator.setDefaults({
highlight: function (element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
success: function (element) {
element.closest('.form-group').removeClass('has-error').addClass('has-success');
},
errorElement: "span",
errorPlacement: function (error, element) {
if (element.is(":radio") || element.is(":checkbox")) {
error.appendTo(element.parent().parent().parent());
} else {
error.appendTo(element.parent());
}
},
errorClass: "help-block m-b-none",
validClass: "help-block m-b-none"
});
//end setDefaults
// validate form setting
var icon = "<i class='fa fa-times-circle'></i> ";
validator=$("#form").validate({
rules: {
name: {
required: true,
minlength: 1
},
pid: {
required: true,
},
},
messages: {
name: {
required: icon + "请输入您的权限名",
minlength: icon + "权限名必须1个字符以上"
},
pid: {
required: icon + "请输入pid",
},
}
});//end validate
$("#btn_save").click(function(){
if($("#form").valid()){
//save
if($("#modaltitle").text()=="添加权限"){
//add
//异步添加数据
$.ajax({
type: "post",
data: {
name:$("#name").val(),
url:$("#url").val(),
pid:$("#pid").val(),
icon:$("#icon").val(),
order_num:$("#order_num").val(),
},
url: "/PermissionController/insert",//后台处理地址
success: function (data) {
if(data.success){
toastr.success(data.msg, '添加成功!');
$("#modal").modal('hide');
datatable.ajax.reload(null, false);//刷新当前页
}else{
toastr.error(data.msg, '错误!');
}
}
}); // end ajax
}else{
//update
//异步修改数据
$.ajax({
type: "post",
data: {
id:$("#id").val(),//主键,从隐藏input获取到
name:$("#name").val(),
url:$("#url").val(),
pid:$("#pid").val(),
icon:$("#icon").val(),
order_num:$("#order_num").val(),
},
url: "/PermissionController/update",//后台处理地址
success: function (data) {
if(data.success){
toastr.success(data.msg, '修改成功!');
$("#modal").modal('hide');
datatable.ajax.reload(null, false);//刷新当前页
}else{
toastr.error(data.msg, '错误!');
}
}
}); // end ajax
}
}
});//end btn_save
});//end ready
</script>
</body>
</html>
点击权限管理菜单的效果: