基于Springboot的角色用户菜单权限系统

假设我们要做一个学校的管理系统,要求不同的角色用户登录进去所看到的内容是不同的,例如校长和门卫登录进去所看到的菜单页面是不同的。校长可以看到全校的摄像头,而门卫看到的摄像头个数则是有限制的。那么如何来实现呢?

首先来分析需要些什么:
1.用户表 user
2.角色表 role
3.菜单表 menu
4.摄像头表 camera
5.用户角色表 roleUser
6.用户菜单表 roleMenu
7.用户摄像头表 roleCamera

以下截图仅供举例参考


基于Springboot的角色用户菜单权限系统_第1张图片
user表字段
基于Springboot的角色用户菜单权限系统_第2张图片
菜单表字段

基于Springboot的角色用户菜单权限系统_第3张图片
菜单表数据库数据

基于Springboot的角色用户菜单权限系统_第4张图片
摄像头表字段

基于Springboot的角色用户菜单权限系统_第5张图片
摄像头表数据库数据
基于Springboot的角色用户菜单权限系统_第6张图片
用户角色关联表

基于Springboot的角色用户菜单权限系统_第7张图片
用户菜单关联表

基于Springboot的角色用户菜单权限系统_第8张图片
用户摄像头关联表

关于表的数据就是这些了,里面的字段根据自己的项目需求添加。
前台的整个执行流程是什么呢?

操作者点击添加用户(这个用户是可以登录平台的)
点击添加用户

基于Springboot的角色用户菜单权限系统_第9张图片
填写资料之后保存

点击保存之后

form表单提交到后台将数据添加到用户表(user)中,这个基本的增删改查不多说了,很简单。
然后写一个角色管理页面,可以配置角色。

基于Springboot的角色用户菜单权限系统_第10张图片
角色管理页面

点击 添加角色


基于Springboot的角色用户菜单权限系统_第11张图片
添加角色编辑页面

点击保存,将数据存入role(角色表)基础的增删改查不多说


基于Springboot的角色用户菜单权限系统_第12张图片
role.png

点击分配用户
基于Springboot的角色用户菜单权限系统_第13张图片
image.png

之前添加的两个用户展现出来,如果选择用户点击保存,则后台将用户的userId和这个角色的roleId保存到roleUser表中

同理,分配菜单和摄像头都是这个流程。

那么,如果菜单分配好了,假设,我给“最高管理者”这个角色分配了四个菜单,“次管理者”这个角色分配了两个菜单,将用户“校长”分配给“最高管理者”这个角色。也就是说,校长这个用户登录进入这个平台的时候应该只能看见四个菜单。
新建一个控制器:platformController

package com.lencity.securitymanagementplatform.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lencity.securitymanagementplatform.data.entity.Camera;
import com.lencity.securitymanagementplatform.data.entity.Menu;
import com.lencity.securitymanagementplatform.data.entity.Role;
import com.lencity.securitymanagementplatform.data.entity.RoleMenu;
import com.lencity.securitymanagementplatform.data.entity.RoleUser;
import com.lencity.securitymanagementplatform.data.entity.User;
import com.lencity.securitymanagementplatform.data.service.MenuService;
import com.lencity.securitymanagementplatform.data.service.RoleMenuService;
import com.lencity.securitymanagementplatform.data.service.RoleUserService;
import com.lencity.securitymanagementplatform.data.service.UserService;

@Controller
@Scope("session")
@RequestMapping("")
public class PlatformController {

   @Autowired
   private UserService userService;
   
   @Autowired
   private RoleUserService roleUserService;
   
   @Autowired
   private RoleMenuService roleMenuService;
   
   @Autowired
   private MenuService menuService;
   

   @GetMapping("/")
   public String index() {
       return "forward:/login.html";
   }

   @PostMapping(value = "/login", produces = "application/json;charset=utf-8")
   @ResponseBody
   public String login(String name, String password, HttpSession session) {
       User user = userService.login(name, password);
       if (user == null) {
           session.removeAttribute("loginUser");
           return "0";
       }
           session.setAttribute("loginUser", user);
           return "1";
       
   }

   @RequestMapping(value = "/logout", produces = "application/json;charset=utf-8")
   @ResponseBody
   public String logout(HttpSession session) {
       session.removeAttribute("user");
       return "1";
   }

   @RequestMapping(value = "/changePassword", produces = "application/json;charset=utf-8")
   @ResponseBody
   public String changePassword(String oldPassword, String newPassword, HttpSession session) {
       User user = (User) session.getAttribute("user");
       boolean result = userService.changePassword(user.getName(), oldPassword, newPassword);
       return result ? "1" : "0";
   }
   
}

JS

function login() {
    $("#form").ajaxSubmit({
        type : 'POST',
        cache : false,
        success : function(result) {
            if (result == "0") {
                alert("帐号或密码错误,请重新输入!");
            } else {
                location.href = "user";
            }
        }
    });
}

接下来就是拦截器


platformInterceptor
package com.lencity.securitymanagementplatform.interceptor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.lencity.securitymanagementplatform.data.entity.Menu;
import com.lencity.securitymanagementplatform.data.entity.RoleMenu;
import com.lencity.securitymanagementplatform.data.entity.RoleUser;
import com.lencity.securitymanagementplatform.data.entity.User;
import com.lencity.securitymanagementplatform.data.service.MenuService;
import com.lencity.securitymanagementplatform.data.service.ModuleService;
import com.lencity.securitymanagementplatform.data.service.RoleMenuService;
import com.lencity.securitymanagementplatform.data.service.RoleUserService;

@Component
public class PlatformInterceptor implements HandlerInterceptor {

  @Autowired
  private ModuleService moduleService;
  
  @Autowired
  private RoleMenuService roleMenuService;
  
  @Autowired
  private RoleUserService roleUserService;
  
  @Autowired
  private MenuService menuService;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
          throws Exception {
      HttpSession session = request.getSession();
      if (session.getAttribute("moduleMenus") == null) {
          session.setAttribute("moduleMenus", moduleService.getModuleMenus());
      }
      User user = (User) session.getAttribute("loginUser");
      if (user != null) {
          RoleUser roleUser = roleUserService.getUserByUserId(user.getId());
          List roleMenus = roleMenuService.getRoleMenuByRoleId(roleUser.getRoleId());
          List menus=new ArrayList<>();
          for (RoleMenu roleMenu : roleMenus) {
              Menu menu = menuService.getMenuById(roleMenu.getMenuId());
              menus.add(menu);
          }
          if (session.getAttribute("indexMenus") == null) {
              session.setAttribute("indexMenus", menus);
          }
          return true;
      } else {
          //response.sendRedirect(request.getContextPath());
          redirect(request, response);
          return false;
      }
  }
  // 对于请求是ajax请求重定向问题的处理方法
      public void redirect(HttpServletRequest request, HttpServletResponse response) {
          // 获取当前请求的路径
          String basePath = request.getContextPath();
          // 如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求,需要特殊处理
          // 否则直接重定向就可以了
          if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
              // 告诉ajax我是重定向
              response.setHeader("REDIRECT", "REDIRECT");
              // 告诉ajax我重定向的路径
              response.setHeader("CONTENTPATH", basePath + "/");
              response.setStatus(HttpServletResponse.SC_FORBIDDEN);
          } else {
              try {
                  response.sendRedirect(basePath + "/");
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }

}

基于Springboot的角色用户菜单权限系统_第14张图片
image.png
package com.lencity.securitymanagementplatform;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.lencity.securitymanagementplatform.interceptor.ModuleInterceptor;
import com.lencity.securitymanagementplatform.interceptor.PlatformInterceptor;

@Configuration
public class PlatformWebConfiguration implements WebMvcConfigurer {

  @Autowired
  private PlatformInterceptor platformInterceptor;
  @Autowired
  private ModuleInterceptor moduleInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
      List platformExcludePathes = new ArrayList<>();
      platformExcludePathes.add("/moduleInterface/**");
      platformExcludePathes.add("/");
      platformExcludePathes.add("/platform/**");
      platformExcludePathes.add("/login.html");
      platformExcludePathes.add("/login");
      platformExcludePathes.add("/publicData/**");
      platformExcludePathes.add("/library/**");
      platformExcludePathes.add("/data/**");
      platformExcludePathes.add("/image/**");
      platformExcludePathes.add("/js/**");
      platformExcludePathes.add("/*.txt");
      registry.addInterceptor(platformInterceptor).addPathPatterns("/**").excludePathPatterns(platformExcludePathes);
      registry.addInterceptor(moduleInterceptor).addPathPatterns("/moduleInterface/**");
      WebMvcConfigurer.super.addInterceptors(registry);
  }

}

通过拦截器,userId去查询roleId,然后通过roleId去查询roleMenu 的菜单id
,最后通过菜单id去查询菜单表。存入session中。

menu.html

循环遍历session中的menus,展现如下效果

基于Springboot的角色用户菜单权限系统_第15张图片
菜单.png

Over~

你可能感兴趣的:(基于Springboot的角色用户菜单权限系统)