JSF2 pass an attribute to backing bean on page load
-
21-07-2021 - |
Question
I have two different JSF2 pages with a shared backing bean. How can I pass a parameter from page to the backing bean (on page load - method with @PostConstruct) so that it knows which page is currently being used.
I know it's possible to use an <f:event>
like preRenderView
(like this), but it then requires a method as well as a field in the backing bean. Is this possible with something like f:attribute or f:param, without any extra method in the backing bean?
Solution
If the bean is request scoped, just get the view ID as managed property by #{view.viewId}
.
@ManagedProperty("#{view.viewId}")
private String viewId; // +setter
If the bean is view scoped, just get the view ID directly by UIViewRoot#viewId()
.
private String viewId;
@PostConstruct
public void init() {
viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId();
// ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow