Switch case alternative for JSF pages
Asked Answered
D

2

5

Other than c:if or c:choose, are there any better ways to implement conditional rendering of 1 component out of several components. Something like switch case for JSF pages?

Diluvium answered 8/2, 2012 at 11:58 Comment(3)
Related: #4870962Granary
@BalusC: could you clarify if it is better to use rendered attribute than using c:if ?Diluvium
I think since I'll have several rendered attributes for multiple components, I may be better off by using a set of if otherwise so that if my first condition has greater probability to be true than I'll be saved from further condition checksDiluvium
G
7

The canonical JSF approach for this is using the rendered attribute. Here are some examples:

<h:someComponent rendered="#{bean.booleanValue}" />
<h:someComponent rendered="#{bean.intValue gt 10}" />
<h:someComponent rendered="#{bean.objectValue eq null}" />
<h:someComponent rendered="#{bean.stringValue ne 'someValue'}" />
<h:someComponent rendered="#{not empty bean.collectionValue}" />
<h:someComponent rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:someComponent rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

The difference with JSTL tags is that the rendered attribute is evaluated during view render time, while JSTL tags are executed during view build time. See also JSTL in JSF2 Facelets... makes sense?

So, if the variables which are necessary for evaluating the condition have a narrower scope than the view scope (i.e. request scope), then you should be using rendered attribute instead. For example, when re-rendering a group of components upon an ajax request. While the JSTL tags could work equally good in this case, they might be evaluated "too early" (i.e. before the action is invoked, which might in turn have changed the conditions) and they would also break the view scope. See also @ViewScoped breaks in tag handlers.

If the variables necessary for evaluating the condition have a broader scope, e.g. session-wide or application-wide or are been hardcoded in some template client, then JSTL tags are more efficient as they will be evaluated during view build time only and not everytime during view render time. See also How to make a grid of JSF composite component?

Granary answered 8/2, 2012 at 19:38 Comment(0)
J
1

You can use rendered attribute:

<h:commandButton rendered="#{value == 'value1'}"/>
<h:commandButton rendered="#{value == 'value2'}"/>

It's not so clear as real case operator, but it is in plain JSF.

Jamie answered 8/2, 2012 at 12:9 Comment(3)
could you clarify if it is better than using c:if & how ?Diluvium
@user Don't know. You don't need to import jstl namespace :)Jamie
Both the books JavaServer Faces by Hans Bergsten and Core JavaServer Faces mention that using c:if is inefficient but not how? Anyways why to use them if you can achieve the same with standard JSF tags.Dharma

© 2022 - 2024 — McMap. All rights reserved.