3

In a web application, users use a servlet HTTP session. Some data are stored in CDI @SessionScoped beans. Later in some pages WebSocket communications are performed between the user browser and the server.

With GlassFish 4, when using an injected @SessionScoped CDI bean from a WebSocket @ServerEndpoint with GlassFish 4.0 I get an error message: org.jboss.weld.context.ContextNotActiveException: WELD-001303 No active contexts for scope type javax.enterprise.context.SessionScoped

From JSP/servlet type requests, using the @SessionScoped CDI bean is fine, but not from the WebSocket @ServerEndpoint.

Also note that using @Singleton CDI beans from the @ServerEndpoint works fine, so this is not a general purpose dependency injection problem.

Maybe I did something wrong.

So my questions is can @SessionScoped CDI beans be used from methods of WebSocket @ServerEndpoint beans? If yes, how?

Thank you for your time.

Florian Beaufumé
  • 1,751
  • 2
  • 22
  • 34
  • Duplicate question to http://stackoverflow.com/questions/20872300/java-ee-7-how-to-inject-an-ejb-into-a-websocket-serverendpoint (short answer, the support for CDI in `javax.websocket` is not well supported, defined, and spec'd) – Joakim Erdfelt Jan 10 '14 at 16:45
  • I think it's not the same question. I update my post to mention that injection of @Singleton CDI beans works fine. This is really a scope issue here. – Florian Beaufumé Jan 10 '14 at 18:58

1 Answers1

0

It may not be the exact same question, but the issue is similar enough that the answers there apply here. Basically, as @JoakimErdfelt notes websocket support for CDI is problematic at best. The websocket spec neglected to mention what scopes are active.

Out of the box, this is what Tyrus supports: https://github.com/tyrus-project/tyrus/tree/master/samples/cdi/src/main/java/org/glassfish/tyrus/sample/cdi

If you want, you can extend it to start a session scope (for reference, Apache DeltaSpike's CDI Context Control), but because of the protocol difference it would be a different session than the one already established via HTTP.

John Ament
  • 11,595
  • 1
  • 36
  • 45