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

查看:83
本文介绍了如何在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文章的链接,该文章涵盖了弹簧HandlerInterceptor.

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或自定义的Filter(过滤器可能是这里的方法).

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).

包装器类

Wrapper Class

  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天全站免登陆