How to insert ConversationScoped beans into a servlet

I need to inject a ConversationScoped bean into a servlet. I use the standard simple @Inject tag, and I call the servlet with the cid parameter, but when it calls some method in the entered bean, I get the following error:

org.jboss.weld.context.ContextNotActiveException : WELD-001303 There are no active contexts for the javax.enterprise.context.ConversationScoped area javax.enterprise.context.ConversationScoped

Can I embed these beans in servlets, or can I only embed Session and Request scoped beans?

+4
source share
2 answers

In a servlet, context is the context of the application, because of which you lose the conversation area. Here is a small utility class that you can use as an anonymous class and wrap the request if you want support for the talk area in servlets ...

 import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import org.jboss.weld.Container; import org.jboss.weld.context.ContextLifecycle; import org.jboss.weld.context.ConversationContext; import org.jboss.weld.servlet.ConversationBeanStore; public abstract class ConversationalHttpRequest { protected HttpServletRequest request; public ConversationalHttpRequest(HttpServletRequest request) { this.request = request; } public abstract void process() throws Exception; public void run() throws ServletException { try { initConversationContext(); process(); } catch (Exception e) { throw new ServletException("Error processing conversational request", e); } finally { cleanupConversationContext(); } } private void initConversationContext() { ConversationContext conversationContext = Container.instance().deploymentServices().get(ContextLifecycle.class).getConversationContext(); conversationContext.setBeanStore(new ConversationBeanStore(request.getSession(), request.getParameter("cid"))); conversationContext.setActive(true); } private void cleanupConversationContext() { ConversationContext conversationContext = Container.instance().deploymentServices().get(ContextLifecycle.class).getConversationContext(); conversationContext.setBeanStore(null); conversationContext.setActive(false); } } 
+1
source

What is equivalent to the ConversationContext proposed in the previous answer in Java EE if we do not use Weld?

0
source

Source: https://habr.com/ru/post/1337474/


All Articles