如何在Servlet中注入ConversationScoped bean
作者:互联网
我需要将一个ConversationScoped bean注入一个servlet.我使用标准的简单@Inject标签,并使用cid参数调用servlet,但是当它调用注入的bean中的任何方法时,我收到以下错误:
org.jboss.weld.context.ContextNotActiveException
:WELD-001303
No active contexts for scope typejavax.enterprise.context.ConversationScoped
我可以在servlet中注入这些bean,还是只能注入Session和Request scoped bean?
解决方法:
在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);
}
}
标签:java,servlets,cdi,jboss-weld 来源: https://codeday.me/bug/20190710/1420734.html