How to send data between views having a ViewScoped bean

久未见 提交于 2019-12-18 12:47:08

问题


Background:

  • I have a ViewScoped bean with a field named someId
  • I have a page, somePage.xhtml with an inputText and a commandLink
  • The value of the inputText has a corresponding field in the bean named searchValue
  • When I click the link a method in the bean redirects to another page called searchResult.xhtml that use the same bean as somePage (although not a requirement)

Before rendering searchResult the bean needs to execute a search in the database, based on the value of the inputText and the variable someId. After that the result shall be shown in searchResult.

Is it possible to do this without:

  • Using a SessionScoped bean, or
  • Having a h:link instead of the commandLink and let f:param's representing someId and the value of the inputText get updated by ajax

I've also tried Flash, but it seems it's not available preRenderView.


回答1:


When you navigate from the page to the searchResult.xhtml the View scoped managed bean is recreated because view scoped bean is still alive until navigation happens so your problem should solve as following:

1-create another managed bean in view scoped for the searchResult.xhtml page and define a variable someId with a set and get method

2-define an action method on your command link (in your first bean) to save the value of someId in a flash scope then navigate to searchResult.xhtml with redirect

public String navigatetosearch() {
    FacesContext.getCurrentInstance().getExternalContext().getFlash().put("someId", someId );
    return "/pages/searchResult?faces-redirect=true";
}

3-in the second bean in get method restore the variable from flash:

public SomeId getSomeId() {
    if (SomeId == null) {
        SomeId =  getFlash().get("SomeId");
    }
    return SomeId;
}

and then you can use this variable in a method in PreRenderView or any place.



来源:https://stackoverflow.com/questions/16817395/how-to-send-data-between-views-having-a-viewscoped-bean

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