首页 > 解决方案 > Jersey/Dropwizard 中的 Spring RequestContextHolder 是什么

问题描述

我是 Dropwizard 的新手,我们需要HttpServletRequest在 AspectJ 项目中获取对象(本机而不是 AOP)。AspectJ项目在不同框架的不同项目中用作框架(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 怎么办?

标签: javaspring-bootjerseyaspectjdropwizard

解决方案


You could inject the HttpServletRequest Object in your code as below

@Inject
private Provider<HttpServletRequest> requestProvider;

You could provide a method in you WebService class to access this request object. In your aspects you could use reflection to invoke this method and access the HttpServletRequest

AspectJ Part: Create an annotation that can be applied over the rest service method that triggers the aspect advice before/around/after method execution based on how you want to write it. Within the advice we invoke the getHTTPServlet method call by fetching the target object from the joinPoint


推荐阅读