如何在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()
方法吗?
如果是这样,在哪里可以调用它们?
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兼容的
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 maunally 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作用域?
- How to choose the right bean scope?
See also:
这篇关于如何在JSF 2.0/2.1中用CDI替换@ManagedBean/@ViewScope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!