gpt4 book ai didi

spring-boot - 如何在 Controller 之前覆盖 SpringBoot 中的 InputStream?

转载 作者:行者123 更新时间:2023-12-05 02:09:50 24 4
gpt4 key购买 nike

如何在到达 Controller 之前覆盖 spring boot 中的@RequestBody 内容?

  1. 我知道在 Controller 之前有 WebMvcConfigurerHandlerInterceptorAdapter 类来处理请求。

  2. 我还用谷歌搜索了 RequestBodyAdviceAdapter

有几个链接不适用于 spring boot。

How to read request.getInputStream() multiple times

How to modify request body before reaching controller in spring boot

现在我可以将输入流读入字符串,进行一些修改并设置回 Controller 的输入流吗?

最佳答案

解决方案1:(我认为更好的解决方案)正如评论中所建议的那样,尝试为对象使用 @JsonProperty 或自定义 De-/Serializer。

解决方案 2:添加 @ControllerAdvice 并实现 RequestBodyAdvice 并覆盖 beforeBodyRead as

@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
InputStream body = inputMessage.getBody();
String bodyStr = IOUtils.toString(body, Charset.forName("UTF-8"));
/*
Update bodyStr as you wish
*/
HttpInputMessage ret = new MappingJacksonInputMessage(new ByteArrayInputStream(bodyStr.getBytes()), inputMessage.getHeaders()); //set the updated bodyStr
return ret;
}

关于spring-boot - 如何在 Controller 之前覆盖 SpringBoot 中的 InputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59543221/

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