So basically you need to calculate the hash of the request body. An elegant way to do this is to apply a decorator to an InputStream .
For example, inside the handler method (in this case you cannot use @RequestBody and you need to create the HttpMessageConverter manually):
@RequestMapping(...) public void handle(HttpServletRequest request) throws IOException { final HashingInputStreamDecorator d = new HashingInputStreamDecorator(request.getInputStream(), secretKey); HttpServletRequest wrapper = new HttpServletRequestWrapper(request) { @Override public ServletInputStream getInputStream() throws IOException { return d; } }; HttpMessageConverter conv = ...; Foo requestBody = (Foo) conv.read(Foo.class, new ServletServerHttpRequest(wrapper)); String hash = d.getHash(); ... }
where the hash is computed incrementally in the read override of the HashingInputStreamDecorator methods.
You can also use @RequestBody if you create a Filter to apply a decorator. In this case, the decorator can pass the calculated hash to the handler method as a request attribute. However, you need to map this filter to the map to apply it only to requests for a specific handler method.
source share