Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare 2 strings with <c:if>?

Tags:

java

jsp

jsf

jstl

I am trying to display a <h:outputText> or <h:commandLink> accordingly to a String property returned by a backing bean. I am having problems when comparing the strings.. Here is the illustration:

<c:if test='#{column.header ne "Details"}'>
     <h:outputText value="#{recordTable[column.property]}"/><br/>
</c:if>
<c:if test='#{column.header eq "Details"}'>
     <h:commandLink value="#{column.header}"
                    action="#{searchBean.goToWarehouse}"/><br/>
</c:if>

However the comparisons are not working. Is this the correct way to do it?? Can it be done without the <jsp:useBean....> as done in: JSP sample

Thanks for any help

like image 803
camiloqp Avatar asked Feb 14 '11 15:02

camiloqp


1 Answers

You seem to be using this in a <h:dataTable>. The JSTL tags are evaluated during view build time only, not during view render time. It boils down to this: JSTL runs from top to bottom first and then hands the produced result over to JSF to run from top to bottom again. At the moment the JSTL tags are evaluated inside a JSF datatable, the datatable's iterated item (the one in var attribute) isn't available to JSTL. Hence the test result is always false.

Just use JSF component's rendered attribute instead.

<h:outputText value="#{recordTable[column.property]}" rendered="#{column.header ne 'Details'}"/>
<h:commandLink value="#{column.header}" rendered="#{column.header eq 'Details'}" action="#{searchBean.goToWarehouse}"/>
<br/>

Here are some more examples how you could utilize the rendered attribute:

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

Unrelated to the concrete problem, Roseindia is not the best JSF learning resource. I'd recommend to head to other resources.

like image 62
BalusC Avatar answered Oct 03 '22 07:10

BalusC