HTTPServletRequest和HTTPServletResponse没有被@Context填充

时间:2018-01-09 22:02:52

标签: dependency-injection jax-rs

我是DI的新手,在JAX-RS中遇到了大量基本问题。

我有一个名为SentryAuthFilter的过滤器,它是一个名为AuthFilter的抽象类的子类。 AuthFilter实施ContainerRequestFilterContainerResponseFilterWriterInterceptor。由于AuthFilter是抽象的,因此configure()matchResource()等方法实际上在SentryAuthFilter()(以及其他类AuthFilter的类中实现。 / p>

SentryFilter中,我需要访问HTTPServletRequest方法中的HTTPServletResponsefilter

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

    ...
 }

问题是requestresponse为空。我已经查看了有关此主题的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除了致电SentryFilterAnotherAuthFilter等之外别无其他,所以我不会在其中使用@Context

很抱歉这篇长篇文章,但我真的很困惑。

0 个答案:

没有答案