美文网首页
7 角色管理

7 角色管理

作者: wqjcarnation | 来源:发表于2020-03-31 20:19 被阅读0次

    变更记录

    表结构变更roleid变为32位字符串,影响的表
    t_role
    t_role_menu
    t_user

    相关文件:
    components/role/findallrole.vue
    components/role/addrole.vue
    components/common/menuchecktree.vue
    AddRoleServlet
    RoleServiceImpl
    RoleDaoImpl

    角色添加的思路

    1、做个简单的列表role/findallrole.vue,里面有一个添加的链接到role/addRole.vue
    2、addRole.vue里需要填写角色基本信息和为角色赋 菜单权限comm/menuchecktree.vue
    普通用户---1,2
    管理员 --1,2,3,4,5,6,7

    相关的代码

    step 1 选择菜单权限

    第1 步,获取选中的节点对象集合
    2、for获取集合中的id,并把id存到menuids里,
    3、提交时,用join方法把数组拼成用逗号分隔的字符串 ,有emit传给父组件。

        <template>
      <div>
      <el-tree
        :props="props"
        :load="loadNode"
        node-key="id"
        ref="tree"
        lazy
        show-checkbox
        @check-change="getCheckedNodes"
        >
      </el-tree>
     <!-- <el-button @click="getCheckedNodes">确定</el-button> -->
      </div>
    </template>
    
    <script>
    
      export default {
          data() {
            return {
              menuids:[],//记录哪些节点被选中
              props: {
                id:0,//新增加的,将来这部分就放菜单的id
                label: 'name',//菜单名字
                children: 'zones',//子菜单
                isLeaf: 'leaf'
              },
            };
          },
          methods: {
            getCheckedNodes() {
              //清空原来的id列表
                    this.menuids.splice(0,this.menuids.length);
                    //console.log("select",this.$refs.tree.getCheckedNodes());//element-ui提供的获取所有被选中的结点
                    //获取选中的节点集合
                    let checks=this.$refs.tree.getCheckedNodes();
                    //循环集合的每一个节点
                   for(let i=0;i<checks.length;i++){
                     //把每个节点的id存放到专用数组里
                     ////bug修正,全选中时因为有0,外键错误,需要把0去除
                      if(checks[i].id!=0){
                      alert(checks[i].id);
                      this.menuids.push(checks[i].id);
                      }
                    }
                    //console.log("menuids",this.menuids);
                    //console.log("menuids_str",this.menuids.join());//1,2,3
                    //所数组转换成用逗号分隔的字符串
                    let menuids_str=this.menuids.join();
                    //alert(menuids_str);
                    //给父组件传过去
                    this.$emit("getIds",menuids_str);
                  },
            loadNode(node, resolve) {
              if (node.level === 0) {
                return resolve([{ id:0,name: 'root' }]);
              }else{//无限级的菜单
                let selid = node.data.id;
                this.$axios.get("http://localhost:8082/vue-servlet/getMenuData?id=" + selid)
                  .then(response => {
                    resolve(response.data.list);
                  })
              }
            }
          }
        };
    </script>
    <style>
    </style>
    

    step 2 开发列表页

      <template>
        <div>
        <div class="nav">
          <el-button type="primary" icon="el-icon-plus" @click="dialogFormVisible = true">新增</el-button>
        </div>
        <el-dialog title="角色添加" :visible.sync="dialogFormVisible" >
                 <addrole></addrole>
        </el-dialog>
        <el-table v-loading="loading" ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="roleName" label="角色名称" width="120">
          </el-table-column>
          <el-table-column prop="roleSort" label="排序" width="200">
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
          </el-table-column>
       <el-table-column prop="delFlag" label="是否删除" width="120">
          </el-table-column>
    
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize" @current-change="changePage">
        </el-pagination>
    
        </div>
      </template>
    
       <script>
         import addrole from '@/components/role/addRole'
              export default {
                data() {
                  return {
                    tableData: [],
                    multipleSelection: [],
                    //以下三个是分页相关的属性
                    total: 0, //查询得到
                    pageSize: 5, //每页条数
                    currentPage: 1,
                    dialogFormVisible: false,
                    loading:true
                  }
                },
                mounted() {
                  //调用查询所有用户的方法
                  this.findAll();
                },
                methods: {
    
                  toggleSelection(rows) {
                    if (rows) {
                      rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                      });
                    } else {
                      this.$refs.multipleTable.clearSelection();
                    }
                  },
                  handleSelectionChange(val) {
                    this.multipleSelection = val;
                  },
                  findAll() {
                    this.loading = false;
                    //请求后台,查询所有用户
                    /*this.$axios.get("http://localhost:8082/vue-servlet/findAllRole", {
                        params: {
                          currentPage: this.currentPage,
                          pageSize: this.pageSize
                        }
                      })
                      .then(response => {
                        let data = response.data; //后台的responseBean
                        //用响应数据去更新
                        this.tableData = data.list;
                        this.total = data.page.count;
                          this.loading = false;
                      })
                      .catch() */
                  },
                  changePage: function(currentPage) {
                    //alert(`当前页${currentPage}`);
                    this.currentPage = currentPage;
                    this.findAll();
                  },
                  handleEdit(index, row) {
                    //console.log(index, row);
                  },
                  handleDelete(index, row) {
                    //console.log(index, row);
                    alert(row.id); //是实体类的属性  是主键,不是索引
                    //请求后台,通过id删除指定用户的信息
                    //删除成功之后,重新调用findall
                  }
                },
                components:{
                  addrole
                }
              }
            </script>
    
            <style>
              .nav {
                text-align: left;
                height: 50px;
                margin: 10px;
              }
    
              .el-main {
                line-height: 0;
              }
    
            </style>
    

    step 3 添加角色页

    <template>
      <div>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="菜单权限" v-model="form.menuids">
                <!-- 需要子组组件把id列表传过来 str-->
                <checktree @getIds="getIds"></checktree>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="form.roleName" placeholder="请输入菜单名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示排序" prop="roleSort">
                <el-input-number v-model="form.roleSort" :min="0" :max="50" label="排序"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示状态" prop="status">
                <el-radio v-model="form.status" label="0">显示</el-radio>
                <el-radio v-model="form.status" label="1">隐藏</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="submitForm('form')">立即创建</el-button>
            <el-button @click="resetForm('form')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    
    </template>
    
    <script>
      import checktree from '@/components/common/menuchecktree'
      export default {
        data() {
          return {
            form: {
              menuids: '',
              roleName: '',
              roleSort: '',
              status: ''
            },
            rules: {
              //required是否必填项  trigger:触发方式 blur:表示离开焦点时   message:错误提示
              roleName: [{
                  required: true,
                  message: '请输入名称',
                  trigger: 'blur'
                },
                {
                  min: 4,
                  max: 20,
                  message: '长度在 6 到 20 个字符',
                  trigger: 'blur'
                }
              ]
            }
          }
        },
        components: {
          checktree
        },
        methods: {
          getIds: function(ids) {
            //alert("addrole:"+ids);
            //把id字符串存到form里
            this.form.menuids = ids;
            //alert("menuids"+this.form.menuids);
          },
          submitForm(formName) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                //alert('submit!');
                //step 1,把form转换成json字符串形式
                let obj = this.$qs.stringify(this.form);
                alert(obj);
                //step 2计划在这里用axios去给后台发送注册请求   (url,data)   data-json
                this.$axios.post('http://localhost:8082/vue-servlet/addRole', obj)
                  .then(response => {
                    alert(response.data.msg);
                  })
                  .catch(error => {
                    console.log(error)
                  })
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          },
          resetForm(formName) {
            this.$refs[formName].resetFields();
          }
        }
      }
    </script>
    
    <style>
    </style>
    

    后台servlet

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String menuids=request.getParameter("menuids");
        System.out.println(menuids);
        String[] menuArray=menuids.split(",");
        System.out.println(menuArray);
        
    }
    

    学生完成上述功能和后台功能

    后台完整版(参考)

    AddRoleServlet

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String roleName=request.getParameter("roleName");
        String roleSort=request.getParameter("roleSort");
        String status=request.getParameter("status");
        String menuids=request.getParameter("menuids");
        String[] menuArray=menuids.split(",");
        //拼装对象
        String roleId=UUIDUtil.generateUUID();
        SysRole obj=new SysRole();
        obj.setRoleId(roleId);
        obj.setRoleName(roleName);
        obj.setRoleSort(roleSort);
        obj.setStatus(status);
        obj.setDelFlag("0");
        //传给servcie进行存储
        IRoleService rs=new RoleServiceImpl();
        ResponseBean rb = null;
        rb = rs.save(obj,menuArray);
        ObjectMapper om=new ObjectMapper();
        String json=om.writeValueAsString(rb);
        response.getWriter().print(json);
    }
    

    RoleServiceImpl

    @Override
    public ResponseBean save(SysRole obj, String[] menuArray) {
        ResponseBean resp = new ResponseBean();
        // 先存储t_role
        int result;
        try {
            result = dao.save(obj);
            if (result > 0) {
                // 如果角色存储成功,再存储角色-菜单的对应关系t_role_menu
                int[] result2=dao.saveRoleAndMenu(obj,menuArray);
                if(result2.length==menuArray.length){
                    resp.setCode("0");
                    resp.setMsg("添加成功");
                }
            } else {
                resp.setCode("-1");
                resp.setMsg("添加失败");
            }
        } catch (ClassNotFoundException | SQLException e) {
            resp.setCode("999");
            resp.setMsg("数据库异常");
        }
        return resp;
    }
    

    RoleDaoImpl

    @Override
    public int save(SysRole obj) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        PreparedStatement ps = null;
        // 加载驱动,定义连接参数,建立连接
        conn = DBUtil.getConnection();
        // 预处理
        ps = conn.prepareStatement("insert into t_role values(?,?,?,?,?)");
        ps.setString(1, obj.getRoleId());
        ps.setString(2, obj.getRoleName());
        ps.setString(3, obj.getRoleSort());
        ps.setString(4, obj.getStatus());
        ps.setString(5, obj.getDelFlag());
        int num = ps.executeUpdate();
        DBUtil.closeDB(null, ps, conn);
        return num;
    }
    
    @Override
    public int[] saveRoleAndMenu(SysRole obj, String[] menuArray) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        PreparedStatement ps = null;
        int[] num = null;
        // 加载驱动,定义连接参数,建立连接
        try {
            conn = DBUtil.getConnection();
            // 开启事务
            // conn.setAutocommit(false)
            DBUtil.beginTransaction(conn);
            // 预处理
            ps = conn.prepareStatement("insert into t_role_menu values(?,?)");
            for (int i = 0; i < menuArray.length; i++) {
                ps.setString(1, obj.getRoleId());
                ps.setString(2, menuArray[i]);
                ps.addBatch();// 批量操作时用他 暂存
            }
            num = ps.executeBatch();// 批量操作
            // 无异常,全部提交
            // conn.commit
            DBUtil.commit(conn);
            conn.setAutoCommit(true);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            // 出现异常,全回滚
            DBUtil.rollback(conn);
            throw new ClassNotFoundException(e.getMessage());
        } catch (SQLException e) {
            e.printStackTrace();
            DBUtil.rollback(conn);
        } finally {
            
                DBUtil.closeDB(null, ps, conn);
            
        }
        return num;
    }
    

    作业:
    1、完成角色添加功能
    2、完成角色列表功能

    相关文章

      网友评论

          本文标题:7 角色管理

          本文链接:https://www.haomeiwen.com/subject/prvguhtx.html