gpt4 book ai didi

json - 使用 Spring 的 @RequestBody 并在之后读取 HttpServletRequest.getInputStream()

转载 作者:可可西里 更新时间:2023-11-01 15:23:53 31 4
gpt4 key购买 nike

我正在使用 Spring 的 @RequestBody 注释和 MappingJacksonHttpMessageConverter 将请求的 JSON POST 数据映射到一个对象中。但是在那之后我想以 String 形式读取数据以进行一些额外的身份验证。但是当编码发生时,HttpServletRequest 中的 InputStream 是空的。一旦我从方法中删除了 @RequestBody 参数,将 POST 数据读取到 String 中就会按预期工作。

我是否必须通过放弃 @RequestBody 并以某种方式手动进行绑定(bind)来妥协,或者是否有更优雅的解决方案?

最佳答案

因此,基本上您需要计算请求正文的哈希值。优雅的方法是对 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();

...
}

其中哈希是在 HashingInputStreamDecorator 的重写 read 方法中递增计算的。

如果您创建一个 Filter 来应用装饰器,您也可以使用 @RequestBody。在这种情况下,装饰器可以将计算出的散列作为请求属性传递给处理程序方法。但是,您需要仔细映射此过滤器,以仅将其应用于对特定处理程序方法的请求。

关于json - 使用 Spring 的 @RequestBody 并在之后读取 HttpServletRequest.getInputStream(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4097012/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com