我是DI的新手,在JAX-RS中遇到了大量基本问题。
我有一个名为SentryAuthFilter
的过滤器,它是一个名为AuthFilter
的抽象类的子类。 AuthFilter
实施ContainerRequestFilter
,ContainerResponseFilter
和WriterInterceptor
。由于AuthFilter
是抽象的,因此configure()
,matchResource()
等方法实际上在SentryAuthFilter()
(以及其他类AuthFilter
的类中实现。 / p>
在SentryFilter
中,我需要访问HTTPServletRequest
方法中的HTTPServletResponse
和filter
。
@Priority(Priorities.AUTHENTICATION)
public class SentryAuthFilter extends AuthFilter {
@Context
private HttpServletRequest request;
@Context
private HttpServletResponse response;
...
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
SentryHttpServletResponseWrapper responseWrapper = new SentryHttpServletResponseWrapper(response);
try {
tomcatSSOFilter.doFilter(request, responseWrapper, (request1, response1) -> {});
} catch (Exception e) {
LOGGER.error("Error occurred executing TomcatSSOFilter", e);
requestContext.abortWith(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build());
return;
}
...
}
问题是request
和response
为空。我已经查看了有关此主题的8个不同问题,但我找不到解释如何注入HTTPServletRequest和HTTPServletResponse的问题。他们只是说它是一个单独的代理对象,你不应该明确地注入它,只需使用@Context
。很明显,@Context
无效。
实际调用SentryFilter
的类或实现AuthFilter
的任何其他类称为DynamicAuthFilter
。此DynamicAuthFilter
已注册"在实现DynamicFeature
@Provider
public class AuthenticationDynamicFeature implements DynamicFeature {
private final List<javax.inject.Provider<? extends AuthFilter>> filterProviders;
/**
* @param permissionAuthFilter permissionAuthFilter
* @param aaaAuthFilter aaaAuthFilter
* @param sentryAuthFilter sentryAuthFilter
*/
@Inject
public AuthenticationDynamicFeature(final javax.inject.Provider<SomeAuthFilter> someAuthFilter,
final javax.inject.Provider<AnotherAuthFilter> anotherAuthFilter,
final javax.inject.Provider<SentryAuthFilter> sentryAuthFilter) {
this.filterProviders = ImmutableList.of(someAuthFilter, anotherAuthFilter, sentryAuthFilter);
}
/**
* {@inheritDoc}
*/
@Override
public void configure(final ResourceInfo resourceInfo, final FeatureContext context) {
List<AuthFilter> filters = filterProviders.stream()
.map(javax.inject.Provider::get)
.filter(f -> f.matchResource(resourceInfo))
.peek(AuthFilter::configure)
.collect(Collectors.collectingAndThen(Collectors.toList(), ImmutableList::copyOf));
context.register(new DynamicAuthFilter(filters));
}
}
根据this,上下文注册似乎是@Context值的填充方式。因此,我不确定问题是AuthenticationDynamicFeature
中的注册是错误的,还是我错过了其他内容。 DynamicAuthFilter
除了致电SentryFilter
,AnotherAuthFilter
等之外别无其他,所以我不会在其中使用@Context
。
很抱歉这篇长篇文章,但我真的很困惑。