【问题标题】:How to inject ConversationScoped beans in a Servlet如何在 Servlet 中注入 ConversationScoped bean
【发布时间】:2011-01-28 13:03:27
【问题描述】:

我需要将ConversationScoped bean 注入到 servlet 中。我使用标准的简单@Inject 标记,并使用 cid 参数调用 servlet,但是当它调用注入 bean 中的任何方法时,我收到以下错误:

org.jboss.weld.context.ContextNotActiveException: WELD-001303 范围类型javax.enterprise.context.ConversationScoped没有活动上下文

我可以在 servlet 中注入这些 bean,还是只能注入 Session 和 Request 范围的 bean?

【问题讨论】:

  • 在您尝试使用 @ConversationScoped bean 时似乎没有对话。您是否在 doGet/doPost 方法中使用它?如果是这样,应该为请求自动创建对话,或者如果您这样做,则由您“手动”开始。

标签: java servlets cdi jboss-weld


【解决方案1】:

在 servlet 中,上下文是应用程序上下文,这就是您放松对话范围的原因。 这是一个小型实用程序类,如果您希望 servlet 中的对话范围支持,您可以将其用作匿名类并包装请求...

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

}

【讨论】:

  • 问题在于,首先,您依赖于 CDI 的 Weld 实现(并且不一定使用您的 Application Server 实现),其次,Container.instance().deploymentServicesprivate
【解决方案2】:

如果我们不使用 Weld,那么在 Java EE 中之前的答案中提出的 ConversationContext 等价物是什么?

【讨论】:

    猜你喜欢
    • 2016-04-06
    • 2015-07-16
    • 2011-06-08
    • 1970-01-01
    • 2014-08-05
    • 2016-11-09
    • 2017-09-24
    • 2013-09-05
    • 1970-01-01
    相关资源
    最近更新 更多