aop (权限控制之功能权限)

在实际web开发过程中通常会存在功能权限的控制,不如这个角色只允许拥有查询权限,这个角色拥有CRUD权限,当然按钮权限显示控制上可以用button.tld来控制,本文就不说明。

具体控制流程就是通过登录系统时候请求控制层将用户的所拥有功能权限查询出来存入session中,然后通过aop切面编程技术获取session里的功能权限与当前方法标签注解权限匹配,当存在则继续执行,若不存在,通过springmvc简单的异常重定向到自己的无权限页面。

1、配置注解方式

privilegeInfo.java

package com.tp.soft.common.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PrivilegeInfo {
    String name() default "";
}

 

2、通过反射获取注解上的标签的封装类

PrivilegeInfoAnnotationParse.java

package com.tp.soft.common.util;

import java.lang.reflect.Method;

public class PrivilegeInfoAnnotationParse {
    public static String parse(Class targetClass, String methodName) throws NoSuchMethodException, SecurityException{
        String privilegeName = "";
        
        Method method = targetClass.getMethod(methodName);
        //判断方法上是否存在@PrivilegeInfo 注解
        if(method.isAnnotationPresent(PrivilegeInfo.class)){
            //获取注解对象
            PrivilegeInfo annotation = method.getAnnotation(PrivilegeInfo.class);
            //获取注解对象上的名字@PrivilegeInfo(name="admin")
            //即name为"admin"
            privilegeName = annotation.name();
            
        }
        return privilegeName;
    }
}

 

3、创建控制层

LoginController.java

具体session创建在之前那一篇文章中有写到,通过拦截器创建的

package com.tp.soft.controller;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.tp.soft.common.util.SysContext;
import com.tp.soft.entity.Privilege;
import com.tp.soft.entity.User;

@Controller
public class LoginController {
    
    @RequestMapping(value = "/login")
    public ModelAndView login() {
        // 这里创建一个对象当做登录成功
        User user = new User();
        user.setLogin_name("taop");
        user.setLogin_pwd("1");

        // 登录查询
        if (user != null) {
            // 根据用户查询出所有权限,本来存入数据库,这边就生动生成taop的权限
            // 不如只有添加权限
            Privilege privilege = new Privilege();
            privilege.setName("query");
            privilege.setDesc("查詢权限");
            List<Privilege> privilegeList = new ArrayList<Privilege>();
            privilegeList.add(privilege);
            SysContext.getSession().setAttribute("privileges", privilegeList);
            SysContext.getSession().setAttribute("user", user);
            return new ModelAndView("/pc/main");
        }
        
        return null;
    }
    
    
    @RequestMapping(value="/toHasNoPower")
    public ModelAndView toHasNoPower(){
        return new ModelAndView("/pc/privilege/noPower");
    }
}

 

UserController.java

package com.tp.soft.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.tp.soft.common.util.PrivilegeInfo;
import com.tp.soft.common.util.SysContext;
import com.tp.soft.entity.Privilege;
import com.tp.soft.entity.User;
import com.tp.soft.service.login.LoginSvc;
import com.tp.soft.service.sys.UserSvc;

@Controller
public class UserController {
    
    @Resource
    private UserSvc userSvc;

    @Resource
    private LoginSvc loginSvc;
    
    @RequestMapping(value="/toQueryUser")
    @PrivilegeInfo(name="query")
    public ModelAndView toQueryUser(){
        User user = userSvc.getUser(21);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", user);
        return new ModelAndView("/pc/userTest");
    }
    
}

 

@PrivilegeInfo(name="query") 可以通过数组的形式 如name={"query", "add"}

创建异常类

AssessDeniedException.java

package com.tp.soft.common.exception;

public class AssessDeniedException extends RuntimeException{

    /**
     * 
     */
    private static final long serialVersionUID = 5188167616201017971L;

    public AssessDeniedException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public AssessDeniedException(String message, Throwable cause,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

    public AssessDeniedException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public AssessDeniedException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public AssessDeniedException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }
    
}

 

创建权限对象

Privilege.java

public class Privilege {
    private int pid;
    private String name;
    private String desc;

...省略set get
}

 

4、配置aop切面类

AdminAspect.java

package com.tp.soft.aop;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import com.tp.soft.common.exception.AssessDeniedException;
import com.tp.soft.common.util.PrivilegeInfoAnnotationParse;
import com.tp.soft.common.util.SysContext;
import com.tp.soft.entity.Privilege;
import com.tp.soft.entity.User;

@Aspect
public class AdminAspect {
    
    @Pointcut("execution(* com.tp.soft.controller..*.*(..)) && !execution(* com.tp.soft.controller.LoginController.*(..))")
    public void pointCutMethod(){
        
    }
    
    @Around("pointCutMethod()")
    public Object  dealPrivilege(ProceedingJoinPoint jpj) throws Throwable{
        //获取请求的类和方法名
        Class<? extends Object> cls = jpj.getTarget().getClass();
        String name = jpj.getSignature().getName();
        System.out.println(cls);
        System.out.println(name);
        
        //获取注解上的标签
        String privilegeName = PrivilegeInfoAnnotationParse.parse(cls, name);
        HttpSession session = SysContext.getSession();
        User user = (User) session.getAttribute("user");
        List<Privilege> privileges = (List<Privilege>) session.getAttribute("privileges");
        if(user == null){
            throw new AssessDeniedException("您无权操作!");
        }
        
        //是否通过访问
        boolean flag = false;
        if(privilegeName == "" || privilegeName == null){
            flag = true;
        }else{
            for (Privilege privilege : privileges) {
                if(privilegeName.equals(privilege.getName())){
                    //用户访问权限(add) 是否包含当前方法的访问权限
                    flag = true;
                    break;
                }
            }
        }
        
        if(flag){
            return jpj.proceed();
        }else{
            //权限不足
            System.out.println("权限不足");
            throw new AssessDeniedException("您无权操作!");
        }
    }
}

 

配置spring-mvc.xml 异常类重定向跳转

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="com.tp.soft.common.exception.AssessDeniedException">forward:/toHasNoPower</prop>
            </props>
        </property>
    </bean>

 

当无权限抛出异常时候即会重定向到toHashNoPower 然后modelandview 自己写的一个无权限的页面

至此全部结束

请求结果:当直接访问查询方法

当访问

 

再访问

 

 

当将权限设置成

 

继续访问

 

转载于:https://www.cnblogs.com/tplovejava/p/7206892.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
课程简介:历经半个多月的时间,Debug亲自撸的 “企业员工角色权限管理平台” 终于完成了。正如字面意思,本课程讲解的是一个真正意义上的、企业级的项目实战,主要介绍了企业级应用系统中后端应用权限的管理,其中主要涵盖了六大核心业务模块、十几张数据库表。 其中的核心业务模块主要包括用户模块、部门模块、岗位模块、角色模块、菜单模块和系统日志模块;与此同时,Debug还亲自撸了额外的附属模块,包括字典管理模块、商品分类模块以及考勤管理模块等等,主要是为了更好地巩固相应的技术栈以及企业应用系统业务模块的开发流程! 核心技术栈列表: 值得介绍的是,本课程在技术栈层面涵盖了前端和后端的大部分常用技术,包括Spring Boot、Spring MVC、Mybatis、Mybatis-Plus、Shiro(身份认证与资源授权跟会话等等)、Spring AOP、防止XSS攻击、防止SQL注入攻击、过滤器Filter、验证码Kaptcha、热部署插件Devtools、POI、Vue、LayUI、ElementUI、JQuery、HTML、Bootstrap、Freemarker、一键打包部署运行工具Wagon等等,如下图所示: 课程内容与收益: 总的来说,本课程是一门具有很强实践性质的“项目实战”课程,即“企业应用员工角色权限管理平台”,主要介绍了当前企业级应用系统中员工、部门、岗位、角色、权限、菜单以及其他实体模块的管理;其中,还重点讲解了如何基于Shiro的资源授权实现员工-角色-操作权限、员工-角色-数据权限的管理;在课程的最后,还介绍了如何实现一键打包上传部署运行项目等等。如下图所示为本权限管理平台的数据库设计图: 以下为项目整体的运行效果截图: 值得一提的是,在本课程中,Debug也向各位小伙伴介绍了如何在企业级应用系统业务模块的开发中,前端到后端再到数据库,最后再到服务器的上线部署运行等流程,如下图所示:

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值