requesbodys.java,之后使用Spring的@RequestBody并读取HttpServletRequest.getInputStream()

I'm mapping my request's JSON POST data into an object using Spring's @RequestBody annotation and MappingJacksonHttpMessageConverter. However after that I'd like to read the data in String form to do some additional authentication. But when the marshalling has happened, the InputStream in HttpServletRequest is empty. Once I remove the @RequestBody parameter from the method the reading of POST data into a String works as expected.

Do I have to compromise by giving up the @RequestBody and doing the binding somehow manually or is there a more elegant solution?

解决方案

So, basically you need to compute a hash of the request body. The elegant way to do it is to apply a decorator to the InputStream.

For example, inside a handler method (in this case you can't use @RequestBody and need to create 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 hash is computed incrementally in overriden read methods of HashingInputStreamDecorator.

You can also use @RequestBody if you create a Filter to apply the decorator. In this case decorator can pass the computed hash to the handler method as a request attribute. However, you need to map this filter carefully to apply it only to the requests to specific handler method.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值