等效于Jersey/Dropwizard中的Spring RequestContextHolder是什么



我是Dropwizard的新手,我们需要在AspectJ项目中获取HttpServletRequest对象(本机而非AOP(。AspectJ项目被用作不同框架的不同项目中的框架(jar(

下面的代码是为spring-boot项目获取HttpServletRequest

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;
}

如何为泽西岛/Dopwizard做?

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

@Inject
private Provider<HttpServletRequest> requestProvider;

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

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

最新更新