JSF 2.0: Preserving component state across multiple views - jsf

The web application I am developing using MyFaces 2.0.3 / PrimeFaces 2.2RC2 is divided into a content and a navigation area. In the navigation area, which is included into multiple pages using templating (i.e. <ui:define>), there are some widgets (e.g. a navigation tree, collapsible panels etc.) of which I want to preserve the component state across views.
For example, let's say I am on the home page. When I navigate to a product details page by clicking on a product in the navigation tree, my Java code triggers a redirect using
navigationHandler.handleNavigation(context, null,
"/detailspage.jsf?faces-redirect=true")
Another way of getting to that details page would be by directly clicking on a product teaser that is shown on the home page. The corresponding <h:link> would lead us to the details page.
In both cases, the expansion state of my navigation tree (a PrimeFaces tree component) and my collapsible panels is lost. I understand this is because the redirect / h:link results in the creation of a new view.
What is the best way of dealing with this? I am already using MyFaces Orchestra in my project along with its conversation scope, but I am not sure if this is of any help here (since I'd have to bind the expansion/collapsed state of the widgets to a backing bean... but as far as I know, this is not possible). Is there a way of telling JSF which component states to propagate to the next view, assuming that the same component exists in that view?
I guess I could need a pointer into the right direction here. Thanks!
Update 1: I just tried binding the panels and the tree to a session-scoped bean, but this seems to have no effect. Also, I guess I would have to bind all child components (if any) manually, so this doesn't seem like the way to go.
Update 2: Binding UI components to non-request scoped beans is not a good idea (see link I posted in a comment below). If there is no easier approach, I might have to proceed as follows:
When a panel is collapsed or the tree is expanded, save the current state in a session-scoped backing bean (!= the UI component itself)
The components' states are stored in a map. The map key is the component's (hopefully) unique, relative ID. I cannot use the whole absolute component path here, since the IDs of the parent naming containers might change if the view changes, assuming these IDs are generated programmatically.
As soon as a new view gets constructed, retrieve the components' states from the map and apply them to the components. For example, in case of the panels, I can set the collapsed attribute to a value retrieved from my session-scoped backing bean.
Update 3: I got it working as described above. To sum it up, the solution is to store the relevant properties in a session-scoped bean instead of making the entire UIComponent session-scoped. Then, when the component is re-constructed after navigation has occurred, set the attribute values by retrieving the saved properties (using EL), e.g.
<p:panel collapsed="#{backingBean.collapsedState}" ... />
(This is a simplified example. Since I am using multiple panels, I am using a map to store these properties, as described above).

One solution would be to use session-scoped beans.

What do you mean by collapsible panels? I ask because there is a component that is closable as well as a component. I am using in the navigation pane in my project. The accordianPanel has an attribute named "activeIndex". Here's what I did in my sessionBean to maintain the state of my accordion tabs:
private int tabIndex; //declared a private variable
public SessionBean() {
tabIndex = 100; //set the initial tab index to 100 so all tabs are closed when page loads.
}
public int getTabIndex(){
return tabIndex;
}
public void setTabIndex(int tabIndex){
this.tabIndex=tabIndex;
}
in my navigation pane:
<p:accordionPanel activeIndex="#{sessionBean.tabIndex}" collapsible="true" autoHeight="false">
<p:tab title="#{tab1_title}">
<h:commandLink value="link here" action="target_page?faces-redirect=true" /><br/>
</p:tab>
<p:tab title="#{tab2_title}">
<h:commandLink value="link here" action="target_page?faces-redirect=true" />
</p:tab>
<p:tab title="#{tab3_title}">
<h:commandLink value="link here" action="target_page?faces-redirect=true" />
</p:tab>
</p:accordionPanel>
I'm not using the tree component for navigation as that presented my project with some difficulties that were easily overcome by using the accordionPanel, so I can't speak to that part of your navigation.

Related

JSF binding doesn't work in the included facet [duplicate]

There are lot of materials out there differentiating value attribute and binding attribute in JSF.
I'm interested in how both approaches differ from each other. Given:
public class User {
private String name;
private UICommand link;
// Getters and setters omitted.
}
<h:form>
<h:commandLink binding="#{user.link}" value="#{user.name}" />
</h:form>
It is pretty straight forward what happens when a value attribute is specified. The getter runs to return the name property value of the User bean. The value is printed to HTML output.
But I couldn't understand how binding works. How does the generated HTML maintain a binding with the link property of the User bean?
Below is the relevant part of the generated output after manual beautification and commenting (note that the id j_id_jsp_1847466274_1 was auto-generated and that there are two hidden input widgets).
I'm using Sun's JSF RI, version 1.2.
<form action="/TestJSF/main.jsf" enctype="application/x-www-form-urlencoded"
id="j_id_jsp_1847466274_1" method="post" name="j_id_jsp_1847466274_1">
<input name="j_id_jsp_1847466274_1" type="hidden" value="j_id_jsp_1847466274_1">
Name
<input autocomplete="off" id="javax.faces.ViewState" name="javax.faces.ViewState"
type="hidden" value="-908991273579182886:-7278326187282654551">
</form>
Where is the binding stored here?
How does it work?
When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding attributes are evaluated (along with id attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding attribute returns a precreated component (i.e. non-null) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding attribute with the autocreated component instance as argument.
In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.
Component instances are request scoped!
Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:
3.1.5 Component Bindings
...
Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed
Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly
recommend that application developers place managed beans that are pointed at by component binding expressions in
“request” scope. This is because placing it in session or application scope would require thread-safety, since
UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on
memory management when placing a component binding in “session” scope.
Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.
And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Threads stuck at 100% CPU utilization in HashMap during JSF saveState(), or even some "strange" IndexOutOfBoundsException or ConcurrentModificationException coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState() or restoreState() methods and like).
Also, as a single component basically references the rest of the entire component tree via getParent() and getChildren(), when binding a single component to a view or session scoped bean, you're essentially saving the entire JSF component tree in the HTTP session for nothing. This will get really costly in terms of available server memory when you have relatively a lot of components in the view.
Using binding on a bean property is bad practice
Regardless, using binding this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value, and perhaps others like styleClass, disabled, rendered, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.
In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent(), new SomeComponent(), getChildren().add() and what not. See also How to refactor snippet of old JSP to some JSF equivalent?
Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>, <h:dataTable>, etc). See also How to dynamically add JSF components.
Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation> to the backing component (i.e. the component identified by <cc:interface componentType>. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?
Only use binding in local scope
However, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding attribute like so binding="#{foo}" and the component is during render response elsewhere in the same view directly as UIComponent reference available by #{foo}. Here are several related questions where such a solution is been used in the answer:
Validate input as required only if certain command button is pressed
How to render a component only if another component is not rendered?
JSF 2 dataTable row index without dataModel
Primefaces dependent selectOneMenu and required="true"
Validate a group of fields as required when at least one of them is filled
How to change css class for the inputfield and label when validation fails?
Getting JSF-defined component with Javascript
Use an EL expression to pass a component ID to a composite component in JSF
(and that's only from the last month...)
See also:
How to use component binding in JSF right ? (request-scoped component in session scoped bean)
View scope: java.io.NotSerializableException: javax.faces.component.html.HtmlInputText
Binding attribute causes duplicate component ID found in the view
each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.
Ensure that every from input has a totaly unique name, so that when the form gets submitted back to to component tree that rendered it, it is easy to tell where each component can read its value form.
The JSF component can generate javascript that submitts back to the serer, the generated javascript knows where each component is bound too, because it was generated by the component.
For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.
http:..../somelink?componentId=123 would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123
The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.

How to change the order of creation/restoring managed beans?

I have a complex problem with order of 'JSF bean life cycle actions'.
I have two beans with different scopes. The first, let's call it, managerBean is session scope bean. The second one, someBean has view scope (someBean really is many different beans). ManagerBean takes some action once per page loading and few others view scope beans are using the results of this action in their constructors.
Everything was working just fine until I've started getting forms IDs in xhtml files from java beans. Now action from managerBean is taken after someBean is created and I'm getting expected result only when the page is reloaded (on refresh, so someBean is using the first results of ManagerBean work).
This is how it looks like now:
<!-- mainTemplate is a main templete of the page which is rendered once
per page view (every other actions are taken via ajax). This is a place
of ManagerBean work after re rendering the page -->
<ui:composition template="/mainTemplate.xhtml">
<ui:define name="mainContent">
<h:form id="#{someBean.formID}">
some inputs
</h:form>
(...)
</ui:define>
</ui:composition>
So when form id was constant String everything worked like I want and now it doesn't. It looks like JSF must calculate ID first and take any other after this (including ManagerBean action).
My question is: Is there a way to change this situation?
If something isn't clear enought, please ask. I was trying to simplify the problem because it has many factors. Maybe all my thinking is wrong (the way I want to take some action per page and some actions after it).
Any help will be good!
The id (and binding) attribute of a JSF UI component is evaluated during view build time. The view build time is that moment when the XHTML source code is turned into a JSF UI component tree. All other attributes of a JSF UI component like value and all events like preRenderView are evaluated/executed after the view build time, usually during view render time (when the JSF UI component tree needs to produce HTML output). This is not something which you can change by just turning a setting or so. It's just the way how JSF works. You can't render something which isn't built yet. You can only change this by writing code the right way.
I can't think of any real world scenario why you need to make the ID attribute dynamic like this. If it were inside a <c:forEach>, or part of dynamic component generation, then okay, but this seems just to be a static form. So I would in first place recommend to forget it and just hardcode the ID in the view and rely on other variables (perhaps a hidden input field? depends all on concrete functional requirement which isn't mentioned anywhere in the question nor guessable based on the code posted so far).
If you really need to make it dynamic, then you need to split the formID property off from the view scoped bean and move it to a different and independent bean, perhaps an application scoped one.
See also:
JSTL in JSF2 Facelets... makes sense? - component's id attribute has same lifecycle as JSTL tags

Naming Container in JSF2/PrimeFaces [duplicate]

This question already has answers here:
How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"
(6 answers)
Closed 6 years ago.
What are the possible naming containers in PrimeFaces? Why it is necessary to append naming container id for Ajax update call when we want to update some UI control on form using update=":mainForm:MainAccordian:userNameTextbox"?
What are the possible naming container in Prime faces
In JSF naming containers derive from UINamingContainer.
why it is necessary to append naming container id for Ajax update call when we want to update some UI control on form using update=":mainForm:MainAccordian:userNameTextbox"
Lets say, <h:outputText value="test1" id="userNameTextbox" /> and you add another <h:outputText value="test2" id="userNameTextbox" /> to your page, you will get an error which says that you have a duplicate ID. You can look it up here at the JavaDoc for UIComponent.setId(String):
Set the component identifier of this UIComponent (if any). Component identifiers must obey the following syntax restrictions:
Must not be a zero-length String.
First character must be a letter or an underscore ('').
Subsequent characters must be a letter, a digit, an underscore (''), or a dash ('-').
.. furthermore, important for you:
The specified identifier must be unique among all the components (including facets) that are descendents of the nearest ancestor UIComponent that is a NamingContainer, or within the scope of the entire component tree if there is no such ancestor that is a NamingContainer.
Means that you cannot have two components with the same ID under the same NamingContainer (if you have no NamingContainer at all, the entire tree is counted as NamingContainer).
Therefore you need to add a NamingContainer, like a <h:form id="myNamingContainer" />
Lets take following example:
<h:outputText value="test1" id="userNameTextbox" />
<h:form id="container1">
<h:outputText value="test2" id="userNameTextbox" />
</h:form>
<h:form id="container2">
<h:outputText value="test3" id="userNameTextbox" />
</h:form>
.. and you want to do an update to userNameTextbox. Which userNameTextbox are you refering to because there are 3?
The first one? Then update userNameTextbox
The second one? Then update container1:userNameTextbox
The third one? Then update container2:userNameTextbox
After having IntelliJ scan all my JARs for implementations of javax.faces.component.NamingContainer here is what I found:
From PrimeFaces 5.3
AccordionPanel
Carousel
Columns
DataGrid
DataList
DataScroller
DataTable
Page
Ring
SubTable
Subview
TabView
TreeTable
UIData
UITabPanel
From MyFaces 2.1
HtmlDataTable
HtmlForm
UITree
UIForm
Naming Containers in Prime Faces
As we can see in JSF Reference
NamingContainer is an interface that must be implemented by any UIComponent that wants to be a naming container. Naming containers affect the behavior of the UIComponent.findComponent(java.lang.String) and UIComponent.getClientId() methods;
So to find Naming Containers in PF you need to check hierarchy of NamingContainer interface. In Eclipse you can do this for example by Ctrl+T shortcut on NamingContainer.
In PF 5.3 there are for example: AccordionPanel, Carousel, Columns, DataGrid, DataList, DataScroller, DataTable, Ring, SubTable, TabView, Tree, TreeTable.
Naming Container influence on component id
Default behavior
Naming Container provide a naming scope for its child components. So it always add prefix to his children id. So id of child component is: parent_component_id".concat(":").concat("component_id").
There is one pro tip that I had read in JavaServer Faces 2.0, The Complete Reference that even if you not add NamingContainer to your page it is always automatically added by JSF itself :) There also exist special algorith of this creation (Chapter 11: Building Custom UI Component -> Box called "Rules for Creating the Top-Level Component for a Composite Component"). Of course when you don't set id, it will be generate automatically (for example j_idt234). So full component id may look like this: "j_idt123:j_idt234:j_idt345".
Change component name separator (since JSF 2.x)
There is a way to override default component name separator (":"). You can define it in web.xml as context-param with name javax.faces.SEPARATOR_CHAR. For example:
<context-param>
<param-name>javax.faces.SEPARATOR_CHAR</param-name>
<param-value>-</param-value>
</context-param>
UIForm attribute "prependId"
To avoid adding scope to child component there is an attribute (only in UIForm component). But this is not recommended solution. Take a look for example at
uiform-with-prependid-false-breaks-fajax-render
Component id usage (for example in "update", "process")
Whole id
You can use whole id: "componentParent:component". This is not recommended (code will be fragile; any id changes will cause need to change ids in many places).
Relative ids in same level of naming container
Inside one naming container you can use simple component id.
PrimeFaces Search Expression Framework
If you don't know this feature please take a look in PrimeFaces documentation. Prime Faces provide Search Expression Framework with couple of very usefull mechanism.
You can search by keywords.
Keywords are the easier way to reference components, they resolve to
ids so that if an id changes, the reference does not need to change.
Core JSF provides a couple of keywords and PrimeFaces provides more
along with composite expression support.
Examples: #this (current component), #form (closest ancestor form), #namingcontainer (closest ancestor naming container), #parent, #widgetVar(name).
You can also mixed those keywords in quite complex paths (Composite Expressions) for example: #form:#parent, #this:#parent:#parent
The second posibility PF gives you are PrimeFaces Selectors (PFS).
PFS integrates jQuery Selector API with JSF component referencing
model so that referencing can be done using jQuery Selector API
instead of core id based JSF model.
So you can for example:
update all form elements by update="#(form)"
update all datatables by update="#(.ui-datatable)"
update all components that has styleClass named "myStyle" by update="#(.myStyle)"
Quite a powerful tool.

JSF same ID on rendered

Let's say I am using rendered as basically a case statement. I have a label and message for an input field, but I want the field itself to change depending on the case. As such:
<p:inputText id="foo" value="#{myBean.params[paramKey]}"
rendered="#{paramIsInput}" />
<p:calendar id="foo" value="#{myBean.params[paramKey]}"
rendered="#{paramIsCalendar}" />
If I do that then I get the following error: java.lang.IllegalStateException: Component ID j_idt64:foo has already been found in the view.
As a workaround I created lots of labels/messages for each param type and changed their ids. But this brings my question. If only one component with an id is actually rendered, why would it matter that I have multiple defined in my jsf file? Is there a way to keep them with all the same ID?
JSF component IDs are supposed to be unique during view build time already, not during view render time only. This way you effectively end up with two JSF components with the same ID which is indeed invalid. You'd like to effectively end up with one JSF component with the desired ID in the JSF component tree after view build time.
You can achieve this by populating the component during the view build time instead of generating its HTML output conditionally during the view render time. You can use the JSTL <c:if> tag for this.
<c:if test="#{paramIsInput}">
<p:inputText id="foo" value="#{myBean.params[paramKey]}" />
</c:if>
<c:if test="#{paramIsCalendar}">
<p:calendar id="foo" value="#{myBean.params[paramKey]}" />
</c:if>
This has however caveats: the <c:if test> condition can't depend on a variable which is only known during JSF render time. So it has not to depend on var of a JSF iterating component, or to be a property of a view scoped bean, etc.
See also:
JSTL in JSF2 Facelets... makes sense?
If only one component with an id is actually rendered, why would it matter that I have multiple defined in my jsf file?
How would JSF know that only one component will be rendered? You are using EL in rendered and both can evaluate to true. Here is the documentation which says you can't have duplicate ids inside a naming container.
The specified identifier must be unique among all the components (including facets) that are descendents of the nearest ancestor UIComponent that is a NamingContainer, or within the scope of the entire component tree if there is no such ancestor that is a NamingContainer.
-
Is there a way to keep them with all the same ID?
In case you still want to have same ids on more than one components you need to separate the naming container.
You can use PanelGrid as a naming container.

whats the practice to write a review page in JSF?

I have a JSF Page which gets few inputs from the User, I want to show a review page to the user - as what he has given as inputs in the previous page. I am using h:OutputText in the review page to show all the inputs the User had given - but when the user has reviewed and if the user wants to save them - I have a commandButton which is bound to an action method in the backing bean - which will not submit any values as the outputTexts are not submitted. What are the options do I have to show a review page at the same time get the values at the server side - I dont want to have the bean session-scoped.
I am using Apache My faces Implementation of JSF 1.2 without any component libs.
You can use h:inputHidden to retain data for the subsequent POST request. E.g.
<h:outputText value="#{bean.property}" />
<h:inputHidden value="#{bean.property}" />
When you don't have an aversion against component libraries, I'd have suggested Tomahawk's t:saveState for this. This way you don't need to specify every property separately in a hidden field.
<t:saveState value="#{bean}" />
When you're already on JSF 2.0, just putting the bean in the view scope would have been sufficient (assuming that you're conditionally rendering input form and review form in the same view). This way it lives as long as you're interacting with the same view.
#ManagedBean
#ViewScoped
public class Bean {
// ...
}

Resources