In the following scenario, the "hasA" condition is checked twice, is there a way to mimic this much similar 开发者_JAVA技巧to a if/else block so that the condition is evaluated only once
<s:decorate template="/layout/display.xhtml">
<h:outputText value="Print A." rendered="#{hasA}"/>
<h:outputText value="Print B." rendered="#{!hasA}"/>
</s:decorate>
You can write the condition in value attribute with EL expression
<h:outputText value="#{hasA ? 'Print A.' : 'Print B.'}" />
To circumvent the problem, you can make sure the getter does not do any complicated stuff twice or basically returns a boolean. You should also make sure the getter is indempotent: calling it twice should yield the same result. To do so, you can either
- Compute lazily the boolean value and store it in a temporary field so that the second time the pre-computed value is returned.
- Change the logic so that the action that would result in a change of the boolean does actually update the boolean field, and the getter/setter is really just a getter/setter and does not compute anything.
The explanation is not crystal clear, but you should see the idea. I don't see anything wrong with having a simple getter evaluated multiple time.
精彩评论