spring boot实现AOP登录拦截

1.在pom.xml中添加配置

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.10</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.10</version>
        </dependency>

2.新建拦截类LoginIntercept.java

package com.llltony.springboot.controller;


import com.llltony.springboot.bean.Employee;
import com.llltony.springboot.bean.ResultMap;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

//AOP做登录拦截
@Component
@Aspect
public class LoginIntercept {

    private static final Logger logger = LoggerFactory.getLogger(LoginIntercept.class);
    @Pointcut("within(com.llltony.springboot.controller..*) && !within(com.llltony.springboot.controller.LoginController)")
    public void pointCut() {
    }
    @Around("pointCut()")
    public Object trackInfo(ProceedingJoinPoint pjp) throws Throwable {
        HttpSession session= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
        Employee user = (Employee) session.getAttribute("userInfo");
        String userRole = (String) session.getAttribute("userRole");
        ResultMap obj= new ResultMap();
        if(user == null) {
            logger.info("-------------没有登录-------------");
            obj.setMessage("未登录");
            obj.setStatus("500");
            return obj;
        }
        return pjp.proceed();
    }

}

3.结果bean类

package com.llltony.springboot.bean;

public class ResultMap {

    String  message;

    String  status;

    public String getMessage() {
        return message;
    }

    public String getStatus() {
        return status;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

转载于:https://www.cnblogs.com/LiLiliang/p/10012835.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值