【问题标题】:What is the equivalent of Spring RequestContextHolder in Jersey/DropwizardJersey/Dropwizard 中的 Spring RequestContextHolder 是什么
【发布时间】:2021-03-06 21:49:56
【问题描述】:

我是 Dropwizard 的新手,我们需要在 AspectJ 项目中获取 HttpServletRequest 对象(本机而不是 AOP)。 AspectJ项目在不同framework的不同项目中作为framework(jar)使用

下面的代码是获取 HttpServletRequest 用于 Spring Boot 项目。

Class<?> requestHolder = Class.forName("org.springframework.web.context.request.RequestContextHolder");
Method method = requestHolder.getMethod("currentRequestAttributes");
Object currentAttributes = method.invoke(requestHolder);
Class<?> servletAttributes = Class.forName("org.springframework.web.context.request.ServletRequestAttributes");
currentAttributes = servletAttributes.cast(currentAttributes);
method = currentAttributes.getClass().getMethod("getRequest");
Object httpRequest = method.invoke(currentAttributes);
if (httpRequest instanceof HttpServletRequest) {
    return (HttpServletRequest) httpRequest;
}

Jersey/Dopwizard 怎么办?

【问题讨论】:

  • 没有等价物,但我想您可以轻松制作类似的东西。看看源代码就行了。
  • @PaulSamsotha 我在泽西岛无法理解,可以从那里获取 httpservelet 对象
  • 请求中的最早点将在 servlet 过滤器中。
  • 您甚至可以尝试使用注入系统。不幸的是,我对 AspectJ 的了解不够,无法提供任何指导。 HttpServletRequest 当然可以在 Jersey 应用程序的任何地方注入。

标签: java spring-boot jersey aspectj dropwizard


【解决方案1】:

您可以在代码中注入 HttpServletRequest 对象,如下所示

@Inject
private Provider<HttpServletRequest> requestProvider;

你可以在你的 WebService 类中提供一个方法来访问这个请求对象。 在您的方面,您可以使用反射来调用此方法并访问 HttpServletRequest

AspectJ 部分: 创建一个可以应用于其余服务方法的注释,该方法根据您的编写方式在方法执行之前/周围/之后触发方面建议。在通知中,我们通过从 joinPoint 获取目标对象来调用 getHTTPServlet 方法

【讨论】:

  • 创建一个注解,该注解可以应用于其他服务方法,根据您的编写方式在方法执行之前/周围/之后触发方面建议。在通知中,我们通过从 joinPoint 获取目标对象来调用 getHTTPServlet 方法。
猜你喜欢
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 2014-12-24
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多