如何在 JSF 2.0/2.1 中用 CDI 替换 @ManagedBean/@ViewScope [英] How to replace @ManagedBean / @ViewScope by CDI in JSF 2.0/2.1
问题描述
我目前正在使用 RichFaces 评估 Java EE 6/JSF 2.1.
I'm currently evaluating Java EE 6 / JSF 2.1 with RichFaces.
声明为
@ManagedBean
@ViewScoped
- 获取 ID 集(准备删除操作等).
- 通过 JSF 显示一个确认弹出窗口.
- 如果用户确认,则调用 delete 方法并删除在步骤 1 中为其存储 ID 的行.
由于 CDI bean 没有 ViewScope,我尝试将 bean 声明为:
Since CDI beans don't have a ViewScope I tried to declare the bean as:
@Named
@ConversationScoped
现在处理在步骤 3 中失败.因为在步骤 1 中设置的值(已检查)不再可用.
Now the processing fails in step 3. because the value that was set in step 1 (checked that) is no longer available.
我是否必须使用 Conversation.begin()
和 Conversation.end()
方法?
Do I have to use Conversation.begin()
and Conversation.end()
methods?
如果是这样,哪里是调用它们的好地方?
If so, where would be good place to invoke them?
推荐答案
如果您可以升级到 JSF 2.2,请立即升级.它提供了一个原生的 @ViewScoped
CDI 注释.
If you can upgrade to JSF 2.2, immediately do it. It offers a native @ViewScoped
annotation for CDI.
import javax.faces.view.ViewScoped;
import javax.inject.Named;
@Named
@ViewScoped
public class Bean implements Serializable {
// ...
}
或者,安装 OmniFaces,它带来了自己的 CDI 兼容 @ViewScoped
,包括一个有效的 @PreDestroy
(在 JSF @ViewScoped
).
Alternatively, install OmniFaces which brings its own CDI compatible @ViewScoped
, including a working @PreDestroy
(which is broken on JSF @ViewScoped
).
import javax.inject.Named;
import org.omnifaces.cdi.ViewScoped;
@Named
@ViewScoped
public class Bean implements Serializable {
// ...
}
另一种选择是安装 MyFaces CODI,它透明地桥接 JSF 2.0/2.1 @ViewScoped
到 CDI.这只会向 URL 添加一个自动生成的请求参数(就像 @ConversationScoped
那样).
Another alternative is to install MyFaces CODI which transparently bridges JSF 2.0/2.1 @ViewScoped
to CDI. This only adds an autogenerated request parameter to the URL (like @ConversationScoped
would do).
import javax.faces.bean.ViewScoped;
import javax.inject.Named;
@Named
@ViewScoped
public class Bean implements Serializable {
// ...
}
如果你真的需要使用@ConversationScoped
,那么你确实需要手动开始和结束它.您需要 @Inject
一个 Conversation
并在最新的 @PostConstruct
和 end()
中调用 begin()
对话的步骤,通常是重定向到新视图的操作方法.
If you really need to use @ConversationScoped
, then you indeed need to manually begin and end it. You need to @Inject
a Conversation
and invoke begin()
in the @PostConstruct
and end()
in the latest step of the conversation, usually an action method which redirects to a new view.
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Named;
@Named
@ConversationScoped
public class Bean implements Serializable {
@Inject
private Conversation conversation;
// ...
@PostConstruct
public void init() {
conversation.begin();
}
public String submit() {
// ...
conversation.end();
return "some.xhtml?faces-redirect=true";
}
}
另见:
- 如何选择合适的 bean 范围?
这篇关于如何在 JSF 2.0/2.1 中用 CDI 替换 @ManagedBean/@ViewScope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!