【问题标题】:Using Spring RequestContextListener使用 Spring RequestContextListener
【发布时间】:2018-07-26 17:38:54
【问题描述】:

如果我使用

@Autowired HttpServletRequest httpServletRequest;

我收到一个错误:

未找到线程绑定请求:您指的是请求属性吗 在实际 Web 请求之外,或在 最初的接收线程?如果您实际上是在 一个网络请求,仍然收到此消息,您的代码可能是 在 DispatcherServlet/DispatcherPortlet 之外运行:在这种情况下, 使用 RequestContextListener 或 RequestContextFilter 来公开 当前请求。

然后在谷歌搜索时,我被要求使用:

<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>

我能够从请求中获取 IP 地址。我的问题是,如果我在 Async 方法中使用它,当有多个并行请求时,IP 地址是否正确。

这是一个 spring mvc 应用程序。有没有更好的方法来获取IP地址。我想在我的自定义提供程序中记录 IP 地址。

【问题讨论】:

  • 在@Async 中,您不会使用RequestContextListener 获得IP 地址。如果你在调用服务@Async方法,你可以将IP inside参数传递给方法。获取IP的方法对于其他场景是正确的,但据我所知,@Async它不起作用。

标签: java spring-mvc spring-security


【解决方案1】:

我认为您以错误的方式使用它。 您可以在控制器方法调用中获取HttpServletRequest

@RestController
public class SomeController {

   @RequestMapping(path = "/dosmtng")
   public void doSomething(HttpServletRequest request, <other params>){
      ....
   }

}

例如,像这样。 所以你可以在这里从请求中获取必要的属性并将它们放在其他方法中。

【讨论】:

    猜你喜欢
    • 2014-12-19
    • 2015-07-27
    • 1970-01-01
    • 2016-11-07
    • 2016-06-09
    • 1970-01-01
    • 2018-01-05
    • 2020-12-19
    • 2018-08-18
    相关资源
    最近更新 更多