如何在spring boot中到达控制器之前修改请求正文 [英] How to modify request body before reaching controller in spring boot

查看:41
本文介绍了如何在spring boot中到达控制器之前修改请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Spring Boot 应用程序.我更改了每个帖子请求的请求正文.是否可以在请求到达控制器之前修改请求正文.请举例说明.

I have a spring boot application. I change the request body of every post request. Is it possible to modify the request body before the request reaches the controller. Please include an example.

推荐答案

简短回答
是的,但并不容易.

Short Answer
Yes, but not easily.

详情
我知道更改请求正文的三个选项之前"它到达控制器中的处理程序方法;

Details
I know of three options to change the body of a request "before" it arrives at the handler method in the controller;

  1. 在调用方法之前使用 AOP 更改请求.
  2. 创建一个 HTTP 过滤器.
  3. 创建自定义 Spring HandlerInterceptor.

既然你已经在使用 spring-boot,选项 3,自定义 Spring HandlerInterceptor,似乎是您的最佳选择.

Since you are already using spring-boot, option 3, custom Spring HandlerInterceptor, seems like the best option for you.

这是一个Baeldung文章的链接,该文章涵盖了spring HandlerInterceptors.

Here is a link to a Baeldung Article covering spring HandlerInterceptors.

Baeldung 文章不是您问题的完整答案因为你只能读取一次HttpServletRequest返回的InputStrem.

The Baeldung article is not the full answer for your problem because you can only read the InputStrem returned by HttpServletRequest one time.

您需要创建一个扩展 HttpServletRequest 的包装类并将您的包装类中的每个请求包装在您的自定义 HandlerInterceptor 或自定义过滤器中(过滤器可能是这里的方法).

You will need to create a wrapper class that extends HttpServletRequest and wrap every request in your wrapper class within your custom HandlerInterceptor or in a custom Filter (Filter might be the way to go here).

包装类

  1. 读取包装类构造函数中的HttpServletRequest InputStream
  2. 根据您的要求修改正文.
  3. 将修改后的正文写入 ByteArrayOutputStream.
  4. 使用 toByteArray 从流中检索实际的 byte[].
  5. 关闭 ByteArrayOutputStream(try-with-resources 对此很有用).
  6. 覆盖 getInputStream 方法.
  7. 每次调用 getInputStream 时,将 byte[] 包装在 ByteArrayInputStream 中.返回此流.
  1. Read the HttpServletRequest InputStream in the wrapper class constructor
  2. Modify the body per your requirements.
  3. Write the modified body to a ByteArrayOutputStream.
  4. Use toByteArray to retrieve the actual byte[] from the stream.
  5. Close the ByteArrayOutputStream (try-with-resources is good for this).
  6. Override the getInputStream method.
  7. Wrap the byte[] in a ByteArrayInputStream every time the getInputStream is called. Return this stream.

如何包装请求

  1. 在您的过滤器中,实例化您的包装类并传入原始请求(它是 doFilter 方法的参数).
  2. 将包装器传递给 chain.doFilter 方法(不是原始请求).

这篇关于如何在spring boot中到达控制器之前修改请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆