实训作业————添加权限

UserController

package com.zhongruan.controller;


import com.zhongruan.bean.PageInfo;
import com.zhongruan.bean.Role;
import com.zhongruan.bean.UserRole;
import com.zhongruan.bean.User;
import com.zhongruan.service.IRoleService;
import com.zhongruan.service.IUserService;
import com.zhongruan.service.impl.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @RequestMapping("/login.do")
    public ModelAndView login(User user, HttpSession session){
        int id = userService.login(user.getUsername(), user.getPassword());
        ModelAndView modelAndView=new ModelAndView();
        if(id!=-1){
            List<Integer> roleIds = roleService.findRoleId(id);
            session.setAttribute("roleIds",roleIds);
            session.setAttribute("user",user);
            modelAndView.setViewName("main");
        }else {
            modelAndView.setViewName("../failer");
        }
       return modelAndView;

    }

    @RequestMapping("/findAll.do")
    public ModelAndView findAll(@RequestParam(defaultValue = "1") int currentPage,String username,@RequestParam(defaultValue = "0") int type,HttpSession session){
        //当搜索的时候
        if(type==1){
            session.setAttribute("searchname",username);
        }else {
            username = (String) session.getAttribute("searchname");
        }

        PageInfo<User> pageInfo = userService.findAll(currentPage,username);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("pageInfo",pageInfo);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    @RequestMapping("/deleteById.do")
    public String delete(int id){
        userService.deleteById(id);
        return "redirect:findAll.do";
    }

    @RequestMapping("/add.do")
    public String add(User user){
        userService.add(user);
        return "redirect:findAll.do";
    }

    @RequestMapping("toUpdate.do")
    public ModelAndView toUpdate(int id){
        User user = userService.selectUserById(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user-update");
        modelAndView.addObject("user",user);
        return modelAndView;
    }

    @RequestMapping("/Update.do")
    public String Update(User user){
        userService.Update(user);
        return "redirect:findAll.do";
    }

    @RequestMapping("/deleteAll.do")
    public String deleteAll(String userList){
        String[] strs = userList.split(",");
        List<Integer> ids = new ArrayList<>();
        for(String s:strs){
            ids.add(Integer.parseInt(s));
        }
        userService.deleteAll(ids);
        return "redirect:findAll.do";
    }

    @RequestMapping("/toAddRole.do")
    public ModelAndView toAddRole(int id,HttpSession session){
        List<Role> roleList = roleService.findRoleByUserId(id);
        session.setAttribute("roleId",id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("roles",roleList);
        mv.setViewName("user-role-add");
        return mv;
    }

    @RequestMapping("/AddRole.do")
    public String addRole(String roleList, HttpSession session){
        UserRole userRole=new UserRole();
        String[] strs = roleList.split(",");
        List<Integer> ids=new ArrayList<>();
        int id = (int) session.getAttribute("roleId");
        for(String s:strs) {
            ids.add((Integer.parseInt(s)));
        }for(int roleId:ids) {
            userRole.setUserId(id);
            userRole.setRoleId(roleId);
            IRoleService.addRole(userRole);
        }
        return "redirect:findAll.do";
    }
}

RoleMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zhongruan.dao.RoleDao" >
    <select id="findRoleIdByUserId" parameterType="int" resultType="int">
        select roleId from user_role where userId=#{userId}
    </select>
    <select id="findRoleByUserId" parameterType="int" resultType="role">
        SELECT * FROM tb_role WHERE  id NOT IN (SELECT roleId FROM user_role WHERE userId=#{id})
    </select>
    <insert id="addRoleById" parameterType="role">
    insert into user_role(userId,roleId) values(#{userId},#{roleId})
    </insert>
</mapper>

user-role-add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8" isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- 页面meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>数据 - AdminLTE2定制版</title>
<meta name="description" content="AdminLTE2定制版">
<meta name="keywords" content="AdminLTE2定制版">

<!-- Tell the browser to be responsive to screen width -->
<meta
   content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"
   name="viewport">


<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/ionicons/css/ionicons.min.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/iCheck/square/blue.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/morris/morris.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/jvectormap/jquery-jvectormap-1.2.2.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/datepicker/datepicker3.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/daterangepicker/daterangepicker.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/datatables/dataTables.bootstrap.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/treeTable/jquery.treetable.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/treeTable/jquery.treetable.theme.default.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/select2/select2.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/colorpicker/bootstrap-colorpicker.min.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/bootstrap-markdown/css/bootstrap-markdown.min.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/adminLTE/css/AdminLTE.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/adminLTE/css/skins/_all-skins.min.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/css/style.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/ionslider/ion.rangeSlider.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/ionslider/ion.rangeSlider.skinNice.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/bootstrap-slider/slider.css">
<link rel="stylesheet"
   href="${pageContext.request.contextPath}/plugins/bootstrap-datetimepicker/bootstrap-datetimepicker.css">
</head>

<body class="hold-transition skin-purple sidebar-mini">

   <div class="wrapper">

      <!-- 页面头部 -->
      <jsp:include page="header.jsp"></jsp:include>
      <!-- 页面头部 /-->
      <!-- 导航侧栏 -->
      <jsp:include page="aside.jsp"></jsp:include>
      <!-- 导航侧栏 /-->

      <!-- 内容区域 -->
      <div class="content-wrapper">

         <!-- 内容头部 -->
         <section class="content-header">
         <h1>
            用户管理 <small>添加角色表单</small>
         </h1>
         <ol class="breadcrumb">
            <li><a href="${pageContext.request.contextPath}/index.jsp"><i
                  class="fa fa-dashboard"></i> 首页</a></li>
            <li><a
               href="#">用户管理</a></li>
            <li class="active">添加角色表单</li>
         </ol>
         </section>
         <!-- 内容头部 /-->

         <form
            action=""
            method="post">
            <!-- 正文区域 -->
            <section class="content"> 
            
            <input type="hidden" name="userId" value="${user.id}">
            
               <table id="dataList"
                     class="table table-bordered table-striped table-hover dataTable">
                     <thead>
                        <tr>
                           <th class="" style="padding-right: 0px">
                           <input id="selall" 
                              type="checkbox" class="icheckbox_square-blue"></th>
                           <th class="sorting_asc">ID</th>
                           <th class="sorting">角色名称</th>
                           <th class="sorting">角色描述</th>                          
                        </tr>
                     </thead>
                     <tbody>
                        <c:forEach items="${roles}" var="role">
                           <tr>
                              <td>
                              
                              <input name="roleId" type="checkbox" value="${role.id}">
                              
                              </td>
                              <td>${role.id}</td>
                              <td>${role.rolename }</td>
                              <td>${role.roledesc}</td>
                              
                           </tr>
                        </c:forEach>
                     </tbody>

                  </table>
            <!--订单信息/--> <!--工具栏-->
            <div class="box-tools text-center">
               <button type="button" class="btn bg-maroon" οnclick="addRoles()">保存</button>
               <button type="button" class="btn bg-default"
                  οnclick="history.back(-1);">返回</button>
            </div>
            <!--工具栏/--> </section>
            <!-- 正文区域 /-->
         </form>
      </div>
      <!-- 内容区域 /-->

      <!-- 底部导航 -->
      <footer class="main-footer">
      <div class="pull-right hidden-xs">
         <b>Version</b> 1.0.8
      </div>
      <strong>Copyright &copy; 2014-2017 <a
         href="http://www.itcast.cn">研究院研发部</a>.
      </strong> All rights reserved. </footer>
      <!-- 底部导航 /-->

   </div>


   <script
      src="${pageContext.request.contextPath}/plugins/jQuery/jquery-2.2.3.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/jQueryUI/jquery-ui.min.js"></script>
   <script>
      $.widget.bridge('uibutton', $.ui.button);
   </script>
   <script
      src="${pageContext.request.contextPath}/plugins/bootstrap/js/bootstrap.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/raphael/raphael-min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/morris/morris.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/sparkline/jquery.sparkline.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/knob/jquery.knob.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/daterangepicker/moment.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/daterangepicker/daterangepicker.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/daterangepicker/daterangepicker.zh-CN.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/datepicker/bootstrap-datepicker.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/datepicker/locales/bootstrap-datepicker.zh-CN.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/slimScroll/jquery.slimscroll.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/fastclick/fastclick.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/iCheck/icheck.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/adminLTE/js/app.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/treeTable/jquery.treetable.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/select2/select2.full.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/colorpicker/bootstrap-colorpicker.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.zh-CN.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/bootstrap-markdown/js/bootstrap-markdown.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/bootstrap-markdown/locale/bootstrap-markdown.zh.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/bootstrap-markdown/js/markdown.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/bootstrap-markdown/js/to-markdown.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/ckeditor/ckeditor.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/input-mask/jquery.inputmask.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/input-mask/jquery.inputmask.extensions.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/datatables/jquery.dataTables.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/datatables/dataTables.bootstrap.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/chartjs/Chart.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/flot/jquery.flot.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/flot/jquery.flot.resize.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/flot/jquery.flot.pie.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/flot/jquery.flot.categories.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/ionslider/ion.rangeSlider.min.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/bootstrap-slider/bootstrap-slider.js"></script>
   <script
      src="${pageContext.request.contextPath}/plugins/bootstrap-datetimepicker/bootstrap-datetimepicker.min.js"></script>

   <script>
      $(document).ready(function() {
         // 选择框
         $(".select2").select2();

         // WYSIHTML5编辑器
         $(".textarea").wysihtml5({
            locale : 'zh-CN'
         });
         // 全选操作 
         $("#selall").click(function() {
            var clicks = $(this).is(':checked');
            if (!clicks) {
               $("#dataList td input[type='checkbox']").iCheck("uncheck");
            } else {
               $("#dataList td input[type='checkbox']").iCheck("check");
            }
            $(this).data("clicks", !clicks);
         });
      });

      // 设置激活菜单
      function setSidebarActive(tagUri) {
         var liObj = $("#" + tagUri);
         if (liObj.length > 0) {
            liObj.parent().parent().addClass("active");
            liObj.addClass("active");
         }
      }

      function addRoles() {
         var checkedNum=$("input[name='roleId']:checked").length;
         if(checkedNum==0){
            alert("请至少选择一个角色进行添加!!!");
            return;
         }
         if(confirm("确认要添加这些角色吗?")){
            var roleList =new Array();
            $("input[name='roleId']:checked").each(
                  function () {
                     roleList.push($(this).val())
                  }
            );
            alert(roleList);
            $.ajax({
               type:"post",
               url: "${pageContext.request.contextPath}/user/AddRole.do",
               data:{roleList:roleList.toString()},
               success:function () {
                  alert("添加成功");
                  location.reload();

               },
               error:function () {
                  alert("添加失败");

               }
            });
         }
      }
   </script>


</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值