自定义一个注解进行登录拦截

发布于 2018-04-27  388 次阅读


该拦截主要针对未登录用户访问诸如“用户中心”等页面,重定向到登录页面。

一、定义一个注解@LoginFrontCheck

package com.van.dusty.interceptor;

import java.lang.annotation.*;

/** 前台token验证:登录校验
 * @Created with com.xwcloud.interceptor
 * @Author Van
 * @Date 2018/4/29
 */
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginFrontCheck {
    boolean value() default true;
    boolean refreshUserInfo() default false;
}

二、切面的拦截实现

package com.van.dusty.interceptor;

import com.van.dusty.common.enums.ResultCode;
import com.van.dusty.common.result.ResultUtils;
import com.van.dusty.product.MemberProductService;
import com.van.dusty.product.MemberTokenService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import com.alibaba.fastjson.JSONObject;
import com.van.dusty.common.result.ApiResult;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.aspectj.lang.reflect.MethodSignature;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import com.alibaba.dubbo.rpc.RpcContext;
/**
 * @Created with com.xwcloud.interceptor
 * @Author Van
 * @Date 2018/4/29
 */
@Aspect
public class LoginCheckAspect {

    @Autowired(required = false)
    private MemberTokenService memberTokenService;
    //本地异常日志记录对象
    private static final Logger logger = LoggerFactory.getLogger(LoginCheckAspect.class);
    // 切点
    @Pointcut("@within(com.van.dusty.interceptor.LoginFrontCheck)||@annotation(com.van.dusty.interceptor.LoginFrontCheck)")
    public void front() {
    }


    /**
     * 前置通知 用于拦截记录用户的操作
     * @param joinPoint 切点
     */
    @Around("front()")
    public  Object doFront(ProceedingJoinPoint joinPoint) throws Throwable {
//        try {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = AopUtils.getMostSpecificMethod(methodSignature.getMethod(), joinPoint.getTarget().getClass());
        LoginFrontCheck n1 = joinPoint.getTarget().getClass().getAnnotation(LoginFrontCheck.class);
        LoginFrontCheck n2 = method.getAnnotation(LoginFrontCheck.class);
        if (n1 != null || n2 != null) {
            // dubbo隐形传参
            HttpServletRequest request = RpcContext.getContext().getRequest(HttpServletRequest.class);
            String token = request.getParameter("token");
            System.err.println("loginCheck:"+token);
            logger.info("___doFront token:" + token);
            boolean isRefresh = false;
            if (n1 != null && n1.refreshUserInfo()) {
                isRefresh = true;
            }
            if (n2 != null && n2.refreshUserInfo()) {
                isRefresh = true;
            }
            // 校验token是否有效,无效则抛出401异常重定向到登录页
            ApiResult apiResult = memberTokenService.checkToken(token, Boolean.TRUE, isRefresh);
            logger.info("___doFront result:" + JSONObject.toJSONString(apiResult));
            if (apiResult.isSuccess()) {
                request.getSession().setAttribute("member", apiResult.getData());
            }
            boolean force = true;
            if (n1 != null) {
                force = n1.value();
            }
            //以方法上的为主
            if (n2 != null) {
                force = n2.value();
            }
            if (force && !apiResult.isSuccess()) {
                return ResultUtils.setError(ResultCode.ACCOUNT_NOT_LOGIN);
            }
            request.getSession().setAttribute("member", apiResult.getData());
        }
        return joinPoint.proceed();
    }
}

三、开启AOP

<!--开启aop-->
<aop:aspectj-autoproxy/>
<!--添加bean-->
<bean class="com.van.dusty.interceptor.LoginCheckAspect"/>

一个菜菜的Java程序猿的学习笔记