Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ServletContext is invalid in MessageBodyWriter if handling async CompletionStage #5527

Open
rickardoberg opened this issue Feb 6, 2024 · 3 comments

Comments

@rickardoberg
Copy link

My resources return CompletionStage and then I have a MessageBodyWriter for MyType. The issue is that if the CompletionStage is not immediately complete upon returning from resource method then the MessageBodyWriter fails because the ServletContext accessed from HttpServletRequest has already been invalidated and set to null (by Jetty 11).

Is there a way around this so that the HttpServletRequest (injected with Provider in MessageBodyWriter constructor and accessed in the writeTo method) becomes valid again? Or is this just a bug that needs to be fixed in Jersey?

@jansupol
Copy link
Contributor

jansupol commented Feb 6, 2024

The MessageBodyWriter is a singleton, it is not recreated for each request. Whatever injected, it would not be aligned with the current request.

Possibly, you can try to inject InjectionManager class and try to call injectionManager.getInstance(HttpServletRequest.class) in the writeTo method.

The lifecycle of HttpServletRequest class is handled by the Servlet container, i.e. by Jetty. If Jetty invalidates, Jersey cannot prevent that.

@rickardoberg
Copy link
Author

I'm injecting Provider<HttpServletRequest>into the MessageBodyWriter constructor, which in writeTo returns a proxy to the correct object. This part is fine. The issue is that because of the asynchronous nature of returning a CompletionStage<MyType> from the resource the request has not been reassociated correctly with the servletcontext. There's some scope fixing (or similar) that needs to happen before calling writeTo, when the result is a CompletionStage. The main issue is that HttpServletRequest.getServletContext needs to return the correct value.

@jansupol
Copy link
Contributor

jansupol commented Feb 6, 2024

There are two possibilities:

  • The injected HttpServletRequest provided does not belong to the current request
  • Jetty ended the current request and set the HttpServletRequest.getServletContext to return null.

You might be trying to provide request-scoped information outside of a request. The JAX-RS way which avoids the injection is to utilize WriterInterceptor.getProperty during the entity writing and setting up the property in the resource class or in the ContainerFilter where the request-scoped information is available.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants