基於springBoot使用aop與mvc攔截器實現登陸校驗


1.編寫切面類

@Component
@Aspect
@Slf4j
public class SellerAuthorizeAspect {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Pointcut(value = "execution(* com.yzy.sell.Controller.Seller*.*(..))"+
    "&&!execution(* com.yzy.sell.Controller.SellerUserController.*(..))")
    public void verify(){}//配置切面,上面設置了切面的范圍

    @Before(value = "verify()")//配置前置通知,beforeAdvice
    public void doVerify(){
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        Cookie cookie = CookieUtil.get(request, CookieConstant.name);
        //在cookie查詢是否含有token的cookie
        if(cookie==null){
            log.warn("登陸校驗失敗,查詢不到cookie");
            throw new SellerAuthorizeException(); //拋出異常,讓攔截器捕獲,實現登陸攔截
        }
        String tokenValue = stringRedisTemplate.opsForValue().get
                (String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
        if(StringUtils.isEmpty(tokenValue)){
            log.warn("登陸校驗失敗,在redis查詢不到相應的token");
            throw new SellerAuthorizeException();
        }
    }
}

2.編寫handle攔截器捕獲登陸校驗產生的異常

@ControllerAdvice//使用 @ControllerAdvice 實現全局異常處理
public class SellExceptionHandler {
    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    //攔截登陸的異常
    @ExceptionHandler(SellerAuthorizeException.class)
    public String handlerSellException(){
        return "redirect:".concat(projectUrlConfig.getSell())
                .concat("/sell/wechat/qrAuthorize");//跳轉會登陸頁面
    }
}

補充:@controlleradvice注解作用:https://www.cnblogs.com/lenve/p/10748453.html

 

@Component
@Aspect
@Slf4j
public class SellerAuthorizeAspect {

@Autowired
StringRedisTemplate stringRedisTemplate;

@Pointcut(value = "execution(* com.yzy.sell.Controller.Seller*.*(..))"+
"&&!execution(* com.yzy.sell.Controller.SellerUserController.*(..))")
public void verify(){}//配置切面,上面設置了切面的范圍

@Before(value = "verify()")//配置前置通知,beforeAdvice
public void doVerify(){
ServletRequestAttributes requestAttributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
Cookie cookie = CookieUtil.get(request, CookieConstant.name);
//cookie查詢是否含有tokencookie
if(cookie==null){
log.warn("登陸校驗失敗,查詢不到cookie");
throw new SellerAuthorizeException();
}
String tokenValue = stringRedisTemplate.opsForValue().get
(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
if(StringUtils.isEmpty(tokenValue)){
log.warn("登陸校驗失敗,redis查詢不到相應的token");
throw new SellerAuthorizeException();
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM