How to trigger destruction of viewscoped bean?

天涯浪子 提交于 2019-12-21 22:20:30

问题


I have a @ViewScoped-annotated managedbean whose @PostContruct-method fetches a list from database to be displayed in a table in the view.
Now when I delete an item I want the changes to be seen in the view.
To keep this dynamic and reusable I only want to delete from database (not manually from list). So I need to destroy/recreate the bean I suppose. Now I do this by navigating to the same view. But the way I do is not reusable.
Can I just destroy the bean manually or navigate to the same view without explicitly navigating to THAT specific view (reusability)?

I am using JSF 2.1


回答1:


You're already on the right track. viewMap is just like any other map; You can remove a ViewScoped bean by name. Please excuse the atrocious chaining:

FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove("yourBean");



回答2:


One solution I found is to destroy the bean by

FacesContext.getCurrentInstance().getViewRoot().getViewMap().clear();

I am not sure if this is the way to go because it simply destroys every viewscoped bean. It's not that bad in this case, but doesn't feel clean.
I appreciate any thought on that or alternative solutions.




回答3:


When you return a non null value inside a method from an action attribute the Bean gets recreated.

index.xhtml

...
<h:commandButton value="delete" action="bean.delete" />
...

Bean.class

...
public String delete() {
  // do operations
  return "index.xhtml?faces-redirect=true";
}
...


来源:https://stackoverflow.com/questions/19490406/how-to-trigger-destruction-of-viewscoped-bean

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!