美文网首页
Spring Boot Security5 资源菜单按钮动态显示

Spring Boot Security5 资源菜单按钮动态显示

作者: Ceruleano | 来源:发表于2019-08-16 20:23 被阅读0次

    前言

    上篇文章介绍了动态用户角色资源的权限管理,在结尾,也提到了个比较实际的问题

    一般系统是不会让用户去点击了菜单才发现没有权限访问,而是针对不同的用户,动态显示不同的菜单

    简单介绍

    那么怎么实现呢,通过Spring Securiyt的标签和后台动态标签验证就可以解决

    那么,要想引用Spring Security标签,那么就要引入相应的标签库,因为小编这里用的前端模板是Thymeleaf,所以引入标签库如下:

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    </dependency>
    

    注意,因为我这里使用的是 Spring Security5 的版本,所以对应也是

    thymeleaf-extras-springsecurity5

    如果是 Spring Security4 的话对应就是

    thymeleaf-extras-springsecurit4

    然后每个页面只需要在html头部引入

    xmlns:sec="http://www.thymeleaf.org/extras/spring-security"

    即可使用 Spring Security 标签库

    实现

    这里基本介绍就介绍完了,下面开始说下怎么实现的动态显示菜单的问题

    在需要动态显示的菜单上,加上

    <标签 sec:authorize="hasAuthority('key')">

    key则为资源表中的资源标识字段

    那我们看看接上篇文章的代码,现在我想给我的菜单1、菜单2、菜单3动态显示,那么实现代码如下:

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org"
          xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
    <head>
        <meta charset="UTF-8">
        <title>index页</title>
    </head>
    <body>
    index页<br/><br/>
    
    <span sec:authorize="hasAuthority('menu1')">
        <button id="menu1Btn" type="button" onclick="sendAjax('/menu1')">菜单1</button>
    </span>
    
    <span sec:authorize="hasAuthority('menu2')">
        <button id="menu2Btn" type="button" onclick="sendAjax('/menu2')">菜单2</button>
    </span>
    
    <span sec:authorize="hasAuthority('menu3')">
        <button id="menu3Btn" type="button" onclick="sendAjax('/menu3')">菜单3</button>
    </span>
    
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
    <script type="text/javascript">
    
        function sendAjax(url) {
    
            $.ajax({
                type: "GET",
                url: url,
                dataType: "text",
                success: function (data) {
                    console.log(data);
                }
            });
        }
    
    
    
    </script>
    </body>
    </html>
    

    那么到这里我们就算完成了,我们看看效果

    这里我们先用admin管理员角色登录,首页如下:

    image.png

    然后,再用teacher1教师角色登录,首页如下:

    image.png

    最后,再用student1学生角色登录,首页如下:

    image.png

    可以看到,对应不同的权限,显示不同的资源按钮

    那么基本代码和效果也演示完毕了

    demo也已经放到github,获取方式在文章的Spring Boot2 + Spring Security5 系列搭建教程开头篇(1) 结尾处

    如果小伙伴遇到什么问题,或者哪里不明白欢迎评论或私信,也可以在公众号里面私信问都可以,谢谢大家~

    相关文章

      网友评论

          本文标题:Spring Boot Security5 资源菜单按钮动态显示

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