问题
Background:
- I have a
ViewScoped
bean with a field namedsomeId
- I have a page,
somePage.xhtml
with aninputText
and acommandLink
- 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 assomePage
(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 thecommandLink
and letf:param
's representingsomeId
and the value of theinputText
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