How to inject Grizzly Request into Jersey ContainerRequestFilter

只愿长相守 提交于 2019-12-01 11:56:28

I'm surprised you even got the app running, to get to the point where you could find out that request is null. Whenever I tried to run it, I would get an exception on start up, saying that there is no request scope, so the request can't be injected, which is what I expected. Though I couldn't reproduce the NPE, I'm thinking this solution will still solve your problem.

So the Request is a request scoped object, as it changes on every request. But the filter is by its nature, a singleton. So what you need to do, is lazily retrieve it. For that, we can use javax.inject.Provider, as a lazy retrieval mechanism.

Going back to the point in my first paragraph, this was the exception I got on start up

java.lang.IllegalStateException: Not inside a request scope.

This makes sense, as the Request need to be associated with a request scope, and on start up, there is none. A request scope is only present during a request.

So what using the Provider does, is allow us to try and grab the Request when there is a request scope present.

public static class Filter implements ContainerRequestFilter {

    @Context
    private javax.inject.Provider<Request> requestProvider;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        final Request request = requestProvider.get();
        System.out.println(request.getRemoteAddr());
    } 
}

I've tested this and it works as expected.

See Also:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!