将项目添加到请求作用域 Bean 中的列表 [英] Add items to List in Request Scoped Bean
问题描述
我有一个支持 bean,如下所示:
I have a backing bean as following:
@Named
@RequestScoped
public class ClientNewBackingBean {
@Inject
private ClientFacade facade;
private Client client;
Client
类有一个 List
属性等.使用 new ArrayList()
设置 childrenList
时,我可以创建一个新的 Client
.
The Client
class has a List<Child> childrenList
attribute, among others. I'm able to create a new Client
when setting the childrenList
with new ArrayList()
.
在视图中,我有一个输入文本字段和一个 Add Child
按钮.该按钮的属性 actionListener=#{clientNewBackingBean.addChild()}
实现为:
In the view, I have a input text field and an Add Child
button. The button has the attribute actionListener=#{clientNewBackingBean.addChild()}
implemented as:
public void addChild() {
if(client.getChildrenList() == null) {
client.getChildrenList(new ArrayList());
}
Child c = new Child("John Doe");
client.getChildrenList().add(c);
}
每次点击 Add Child
按钮时,都会重新创建 bean,并且视图只显示一个 John Doe 子项(我相信,因为它是请求范围的).除了将 bean 范围更改为 Session 之外,还有其他方法可以解决此问题吗?
Everytime the Add Child
button is clicked, the bean is recreated and the view only shows one John Doe child (due to it being Request scoped, I believe). Is there another way to solve this besides changing the bean scope to Session?
推荐答案
如果您使用标准的 JSF bean 管理注解 @ManagedBean
,您可以通过将 bean 放在视图范围内来解决它来自 @ViewScoped
一>.
If you were using standard JSF bean management annotation @ManagedBean
, you could have solved it by just placing the bean in the view scope by @ViewScoped
.
@ManagedBean
@ViewScoped
public class ClientNewBackingBean implements Serializable {
@EJB
private ClientFacade facade;
// ...
在 CDI 中,@ViewScoped
不存在,最接近的替代方法是 @ConversationScoped
.你只需要自己开始和停止它.
In CDI, the @ViewScoped
however doesn't exist, the closest alternative is @ConversationScoped
. You only have to start and stop it yourself.
@Named
@ConversationScoped
public class ClientNewBackingBean implements Serializable {
@Inject
private Conversation conversation;
// ...
@PostConstruct
public void init() {
conversation.begin();
}
public String submitAndNavigate() {
// ...
conversation.end();
return "someOtherPage?faces-redirect=true";
}
}
您还可以使用 CDI 扩展 MyFaces CODI,它将透明地桥接 JSF @ViewScoped
注释与 @Named
一起正常工作:
You can also use the CDI extension MyFaces CODI which will transparently bridge the JSF @ViewScoped
annotation to work properly together with @Named
:
@Named
@ViewScoped
public class ClientNewBackingBean implements Serializable {
@Inject
private ClientFacade facade;
// ...
CODI 替代方法是使用 @ViewAccessScoped
,只要后续请求引用相同的托管 bean,无论使用的物理视图文件如何,它都会存在.
A CODI alternative is to use @ViewAccessScoped
which lives as long as the subsequent requests reference the very same managed bean, irrespective of the physical view file used.
@Named
@ViewAccessScoped
public class ClientNewBackingBean implements Serializable {
@Inject
private ClientFacade facade;
// ...
另见:
- 如何选择合适的 bean 范围?
- 推荐的 JSF 2.0 CRUD 框架
这篇关于将项目添加到请求作用域 Bean 中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!