Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java interceptor reading request body makes the request empty

I have written an interceptor using spring that reads the request body from the HTTPServletRequest, in preHandle method. Request body contains json. I am able to read the request body also but something is happening to the request object and the request body is getting blank. And beause of this the request is becoming a bad request. Any help will be much appreciated. Thanks in advance.

like image 558
Ritesh Waghela Avatar asked Oct 21 '22 17:10

Ritesh Waghela


1 Answers

I haven't used either JEE interceptors or Spring interceptors and don't know how they work.

But it sounds like the easier way would be to go with a filter (as configured from the web.xml). Since filters call each other in a chain, you could easily replace the HttpServletRequest object that is forwarded with a wrapped one (where you provide the body).

This could probably be accomplished by creating a class of your own, extending the HttpServletRequestWrapper and then override the appropriate methods (getInputStream sounds like the way to go here, yes?).

Your version of getInputStream would then return a ByteArrayInputStream of the body you already read, or whatever you kind of InputStream you feel is appropriate.

like image 62
jsundin Avatar answered Oct 23 '22 10:10

jsundin