【问题标题】:How to get information about HTTP request down the stack of the Spring framework handler method如何从 Spring 框架处理程序方法的堆栈中获取有关 HTTP 请求的信息
【发布时间】:2021-08-21 14:42:12
【问题描述】:

有没有办法从 Spring 请求处理程序方法的调用堆栈中的方法获取有关 HTTP 请求的信息?

换句话说,我有一个处理程序方法,例如:

@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
  MyInternalClass.doSomeAction();
  return String.format("Hello %s!", name);
}

我正在寻找在MyInternalClass 类中的doSomeAction() 静态方法的代码中获取有关HTTP 请求的信息(如URL、标头等)的方法。

限制是我不能修改原来的方法(hello())。

【问题讨论】:

标签: java spring


【解决方案1】:

可以添加HttpServletRequest类型的Request参数

@GetMapping("/hello")
public String hello(
   @RequestParam(value = "name", defaultValue = "World") String name,
   HttpServletRequest originalRequest) {
  // HERE: call another method here
  return String.format("Hello %s!", name);
}

看看Spring Reference Documentation, Chapter "Method Arguments"


第 2 部分

但是,我一直在寻找一种不会强制开发人员更改代码的方法。我将尝试在我的问题中添加一个示例,这样会更详细。

您可以使用RequestContextHolder获取请求属性。

HttpServletRequest request = 
      ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
                .getRequest();

RequestContextHolder.getRequestAttributes() 是一个静态方法,可以从任何地方调用(即使是没有 Spring Bean 的类)。但要求它是从由 HTTP 请求触发的线程中调用的。

【讨论】:

  • 谢谢你,@Ralph。但是,我一直在寻找一种不会强迫开发人员更改代码的方法。我将尝试在我的问题中添加一个示例,这样会更详细。
  • @LeoY 参见 May anser 的第二部分
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多