springboot如何获取前端请求头的值并加入ThreadLocal

依赖:


	org.aspectj
	aspectjweaver
	1.9.7

示例:

public class ThreadLocalUtil {
    private static ThreadLocal<String> aaHeaderValueThreadLocal = new ThreadLocal<>();

    public static void setAAHeaderValue(String aaHeaderValue) {
        aaHeaderValueThreadLocal.set(aaHeaderValue);
    }

    public static String getAAHeaderValue() {
        return aaHeaderValueThreadLocal.get();
    }

    public static void clear() {
        aaHeaderValueThreadLocal.remove();
    }
}
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 MyAnnotation {
}
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class HttpServletRequestUtil {

    public static String getAAHeaderValue() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        return request.getHeader("aaHeader");
    }
}
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class RequireXXAspect {

    @Pointcut("@annotation(com.mySpringSecurity.mySpringSecurity.aspect.MyAnnotation)")
    public void myAnnotationMethod() {
    }

    @Before("myAnnotationMethod() && @annotation(requireXX)")
    public void beforeMethodWithRequireXX(JoinPoint joinPoint, MyAnnotation requireXX) {
        // 获取aaHeader头的值,这里假设通过ServletRequest获取
        String aaHeaderValue = HttpServletRequestUtil.getAAHeaderValue();
        // 将aaHeaderValue存放到ThreadLocal中
        ThreadLocalUtil.setAAHeaderValue(aaHeaderValue);
    }
}

你可能感兴趣的:(spring,boot,java,切面)