hle*_*one 5 spring json http spring-mvc jackson
我正在使用Spring的@RequestBody注释将我的请求的JSON POST数据映射到一个对象MappingJacksonHttpMessageConverter.然而,之后我想读取String表单中的数据以进行一些额外的身份验证.但是当编组发生时,InputStream进入HttpServletRequest是空的.一旦我@RequestBody从方法中删除参数,POST数据的读取就会String按预期工作.
我是否必须通过@RequestBody手动放弃并以某种方式进行绑定来妥协,还是有更优雅的解决方案?
因此,基本上您需要计算请求正文的哈希值。优雅的方法是将装饰器应用于InputStream.
例如,在处理程序方法内(在这种情况下您不能使用@RequestBody并且需要HttpMessageConverter手动创建):
@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();
...
}
Run Code Online (Sandbox Code Playgroud)
read其中哈希是在 的重写方法中增量计算的HashingInputStreamDecorator。
@RequestBody如果您创建一个Filter应用装饰器,也可以使用它。在这种情况下,装饰器可以将计算出的哈希值作为请求属性传递给处理程序方法。但是,您需要仔细映射此过滤器,以仅将其应用于对特定处理程序方法的请求。