Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Request/Response Body&Header in Spring AOP

I want to get request/response body and header within my aspect before and after if it's available or how to get those .

I mean i think with before annotation should be work for request,

with after annotation should be work for response. Can be ?

What I've tried so far :

I tried logbook library it's very complicated for me i could'nt figured it out how to work with that.So i gave up.

The actuator can do trick but I am doing extra work like how many times the endpoints called etc.So therefore i can't use actuator.

Also i tried to get request headers like below at least but i think this headers coming same all the time.I couldn't get httpservletresponse like how httpservetrequest does.

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();

then request.getHeader("date") but what about requestbody ?

how to get requestbody ? responsebody ? repsonseheader ?

My aspect file :

@Aspect
@Component
public class AppAspect implements ResponseInfo{

    @Before("execution(@(@org.springframework.web.bind.annotation.RequestMapping *) * *(..))")
    public void loggingStartPointRequests(JoinPoint joinPoint) {

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();

}

@After("execution(@(@org.springframework.web.bind.annotation.RequestMapping *) * *(..))")
    public void loggingEndPointRequests(JoinPoint joinPoint) throws IOException {

    }

}

My Controller Class:

@RestController
public class MainController {

    @GetMapping("/people") // 
    public ResponseEntity<Poeple> getAllPeople(@RequestParam(name = "page", required = false) Integer page,
            @RequestParam(name = "size", required = false) Integer size,
            @RequestParam(name = "sortBy", required = false) Boolean sortByNameOrEpCount) {
doSomething();
}

}
like image 931
Samet Dağ Avatar asked Feb 17 '26 21:02

Samet Dağ


1 Answers

I had the same problem and if you have your @Aspect annotated with @Component (or any @Autowired candidate) you can simply get the HttpServletRequest like this:

@Aspect
@Component
public class SomeAspect {
    
   @Autowired
   HttpServletRequest request;

   @Before("...")
   public void beforeAdvice(JoinPoint jp){
       /* You will have the current request on the request property */
      System.out.println(request.getRequestURL());
   }  
}

I know this is an old question but I hope it'll be helpful.

like image 70
853174 Avatar answered Feb 20 '26 14:02

853174



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!