spring boot中 使用AOP实现登录权限验证

0.基本概念

  • AOP(Aspect-oriented programming)

    In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding additional behavior to existing code (an advice) without modifying the code itself, instead separately specifying which code is modified via a "pointcut" specification, such as "log all function calls when the function's name begins with 'set'". This allows behaviors that are not central to the business logic (such as logging) to be added to a program without cluttering the code, core to the functionality. AOP forms a basis for aspect-oriented software development.
    在计算中,面向切片的编程(AOP)是一种编程范例,旨在通过允许分离横切关注点来增加模块性。它通过向现有代码(建议)添加额外行为而不修改代码本身,而是通过“切入点”规范分别指定修改哪些代码,例如“当函数名称以'set'开头时记录所有函数调用”。这允许将不是业务逻辑核心的行为(如日志记录)添加到程序中,而不会混淆代码和功能的核心。 AOP构成了面向切片的软件开发的基础。

1.问题描述

在web开发中会涉及到这样一个基本问题,在用户发出一个http请求时,需要验证是否有权访问(在本例中 为是否登录)。若未登录则需要跳转到登录页面,否则响应用户请求。

2.解决方案

1.在 maven 配置文件中 添加AOP依赖

   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
   </dependency>

2.编写验证器

  public class SignVerification {// 登录验证
    ServletRequestAttributes attributes =   (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    HttpSession session= request.getSession();
    public boolean Verification(){
        if (session.getAttribute("Admin") == null)
        {
            return false;
        }
        return true;
    }

   }

3.编写拦截器 VerificationAspect

@Aspect
@Component // 放入spring 容器
public class VerificationAspect {
private final static Logger logger =               LoggerFactory.getLogger(VerificationAspect.class);

//拦截条件
@Pointcut("execution(public * com.freeyun.demo.Controller.ShowInfoController.*(..))")
public void log() {}
@Around("log()")
public Object signVerification(ProceedingJoinPoint pjp) throws Throwable{
    SignVerification v = new SignVerification();
    if (v.Verification())//已经登录
    {
        return pjp.proceed();//继续执行被拦截的方法
    }
    else {//未登录
        //构建JSON 
        String response = "{\"signin\":0}";
        return response;
    }
}
  }

4.前端对收到的JOSN数据进行判断,若未登录则跳转到登录页面

 if(response.signin == 0)
        {

            window.location.href = "登录页面的路径";
        }

转载于:https://www.cnblogs.com/freeyun/p/9448453.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值