7

I have created Spring Boot REST API where all endpoint will have header parameter "sessionGuid". I would like to print that sessionGuid using AOP.

@Before("PointcutDefinition.controllerLayer()")
  public void beforeAdvice(JoinPoint joinPoint)
  {
    Object[] signatureArgs = joinPoint.getArgs();
    for (Object signatureArg : signatureArgs)
    {
      System.out.println("Arg: " + signatureArg);
    }
  }

The above code is printing all the arguments i.e. if my URL is

{{base-url}}/v1/login/users/SOMENAME/status it is printing both SOMENAME (path variable) and "sessionGuid" value. I just want to print the value from the header parameter "sessionGuid".

joinPoint.getArgs(); is returning an array. I don't want to print something like arg[1] since sessionGuid may be the 3rd or 4th argument in different operations.

Is there a way by which i can print only "sessionGuid" from the header.

Thiagarajan Ramanathan
  • 1,035
  • 5
  • 24
  • 32

1 Answers1

19

if you are looking for a solution to your problem you can use directly RequestContextHolder.

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String header = request.getHeader("sessionGuid")

you can also use reflection API if you want to be more generic.

stacker
  • 4,317
  • 2
  • 10
  • 24
  • 1
    A similar thing can also be done using the spring interceptor but the question here as to how to do it using AOP. Knowing and accessing the header values could be useful in an aspect. For e.g. An aspect for Security – AmanKapoor27 May 04 '20 at 18:13
  • Use this for getting jwt token: ```HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); String token = request.getHeader("Authorization").split(" ")[1];``` – Uros Pocek Jan 14 '23 at 02:11
  • Is it thread safe? – Jayesslee Feb 28 '23 at 02:32
  • @Jayesslee yes. – stacker Feb 28 '23 at 12:40