本文介绍了使用带有 RestController 的 ClientHttpRequestInterceptor 拦截传入的客户端请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在传入的请求中附加一些数据.像随机生成的令牌或 uuid 到传入的请求.然后我想通过控制器处理它.我开始了解 ClientHttpRequestInterceptor.但是看看这个 doc,好像只拦截响应,不拦截请求.这是我不看的.有没有其他方法可以做到这一点?

I want to append some data to the incoming request. Like random generated token or uuid to the incoming request. And then I want to process it through the controller. I came to know about ClientHttpRequestInterceptor. But looking at this doc, it seems like it only intercept the response, it doesn't intercept the request. Which is what I am not looking. Is there any other way to do this ?

我怎样才能在我的 RestController 中注册这个拦截?这样在控制器处理请求之前,请求应该已经有数据了.

And how can I register this intercept in my RestController ? So that before controller process the request, the request should already has the data.

我刚刚发现,我可以使用请求正文中的 set 方法直接在控制器中设置数据.这是有效的.但我不确定这是否是推荐的方式.因为据我所知,必须在调度程序 servlet 中修改请求.

I just found out, I can directly set the data in controller using set method in request body. And this is working. But I am not sure if this is recommended way. Because as far as I know the request has to be modified in dispatcher servlet.

请指教.

推荐答案

如果你不想这样做 (如何在spring boot中到达控制器之前修改请求体),您可以执行以下操作之一:

If you don't want to do it this way (How to modify request body before reaching controller in spring boot),you might do one of the following:

  1. OncePerRequestFilter(如@doctore 回答中所述)并向请求添加参数.这将允许您向请求添加数据,但不会更改客户端发送的任何内容.
  2. 在控制器中添加一个方法并在处理开始时调用它.我不太喜欢这种方式,因为与过滤器方法不同,这需要您调用该方法.
  3. [注意:我从来没有尝试过这个,但它应该可以工作]在控制器中输入处理程序方法之前,在[某处]添加一个方法并使用Spring AOP调用它.这很好,但本质上只是您创建自己的处理 OncePerRequestFilter 的方式.
  1. OncePerRequestFilter (as mentioned in the @doctore answer) and add a parameter to the request. This would allow you to add data to the request, but not change anything sent by the client.
  2. Add a method in the controller and call it at the start of processing. I don't like this as much because unlike the filter approach, this requires you to call the method.
  3. [Note: I've never tried this, but it should work] Add a method [somewhere] and use Spring AOP to call it before entering the handler method in the controller. This is fine, but is essentially just you creating your own way of processing a OncePerRequestFilter.

肯定还有其他方法可以用 Spring 做到这一点,我只是不认识他们.

There are surely other ways of doing this with Spring,I just don't know them.

这篇关于使用带有 RestController 的 ClientHttpRequestInterceptor 拦截传入的客户端请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 16:16