Issue
I want to append some data to the incoming request. Like random generated token or uuid to the incoming request. And then I want to process it through the controller. I came to know about ClientHttpRequestInterceptor
. But looking at this doc, it seems like it only intercept the response, it doesn't intercept the request. Which is what I am not looking. Is there any other way to do this ?
And how can I register this intercept in my RestController ? So that before controller process the request, the request should already has the data.
EDIT: I just found out, I can directly set the data in controller using set method in request body. And this is working. But I am not sure if this is recommended way. Because as far as I know the request has to be modified in dispatcher servlet.
Please advice.
Solution
If you don't want to do it this way (How to modify request body before reaching controller in spring boot), you might do one of the following:
OncePerRequestFilter
(as mentioned in the @doctore answer) and add a parameter to the request. This would allow you to add data to the request, but not change anything sent by the client.- Add a method in the controller and call it at the start of processing. I don't like this as much because unlike the filter approach, this requires you to call the method.
- [Note: I've never tried this, but it should work] Add a method [somewhere] and use Spring AOP to call it before entering the handler method in the controller. This is fine, but is essentially just you creating your own way of processing a OncePerRequestFilter.
There are surely other ways of doing this with Spring, I just don't know them.
Answered By - DwB