2011-11-14 7 views
30

Il seguente codice JSF contiene due separati <c:if></c:if>. Diamo un'occhiata.La rappresentazione di if-elseif in EL utilizzando JSF

<?xml version='1.0' encoding='UTF-8' ?> 
<html xmlns="http://www.w3.org/1999/xhtml" 
     xmlns:h="http://java.sun.com/jsf/html" 
     xmlns:c="http://java.sun.com/jsp/jstl/core"> 
    <h:head> 
     <title>JSF EL</title> 
    </h:head> 
    <h:body> 
     <h:form> 

      <c:set scope="request" var="row" property="x" value="10"/> 

      <c:if test="#{row==10}"> 
       <h:outputLabel value="value = 10"/> 
      </c:if> 

      <c:if test="#{row==15}"> 
       <h:outputLabel value="value = 15"/> 
      </c:if> 

     </h:form> 
    </h:body> 
</html> 

visualizza semplicemente value = 10 sulla pagina JSF in fase di esecuzione. Devo rappresentare lo stesso <c:if></c:if> con il seguente if-elseif-else (contesto Java).

if(row.equals(10)) 
{ 
    //Do something...(JSF stuff) 
} 
else if(row.equals(15)) 
{ 
    //Do something...(JSF stuff) 
} 
else 
{ 
    //Do something...(JSF stuff) 
} 

Come può essere rappresentato con Expression Language (EL) utilizzando JSF?

+0

possibile duplicato del [condizionale visualizzazione di elementi HTML] (http://stackoverflow.com/questions/4870462/conditionally-displaying-html-elements) – BalusC

risposta

41

Il codice seguente il modo più semplice:

<h:outputLabel value="value = 10" rendered="#{row == 10}" /> 
<h:outputLabel value="value = 15" rendered="#{row == 15}" /> 
<h:outputLabel value="value xyz" rendered="#{row != 15 and row != 10}" /> 

Link per la sintassi delle espressioni EL. http://developers.sun.com/docs/jscreator/help/jsp-jsfel/jsf_expression_language_intro.html#syntax

+0

Va notato che l'attributo 'rendered' si applica al fase 'render', il che significa che tutto ciò che è all'interno verrà valutato completamente. Se un grande componente non è reso (come questo) potrebbe significare che potrebbe essere eseguito un sacco di codice e i risultati verranno buttati via. – KarlP

45

È possibile utilizzare EL se si desidera lavorare come se:

<h:outputLabel value="#{row==10? '10' : '15'}"/> 

Cambiare stili o classi:

style="#{test eq testMB.test? 'font-weight:bold' : 'font-weight:normal'}" 

class="#{test eq testMB.test? 'divRred' : 'divGreen'}" 
+1

c'è un modo simile di usare un if senza altro? – sree

8

è possibile utilizzare "ELSE IF" utilizzando operatore condizionale nel linguaggio delle espressioni come di seguito:

<p:outputLabel value="#{transaction.status.equals('PNDNG')?'Pending': 
            transaction.status.equals('RJCTD')?'Rejected': 
            transaction.status.equals('CNFRMD')?'Confirmed': 
            transaction.status.equals('PSTD')?'Posted':''}"/> 
2

Una possibile soluzione è:

<h:panelGroup rendered="#{bean.row == 10}"> 
    <div class="text-success"> 
     <h:outputText value="#{bean.row}"/> 
    </div> 
</h:panelGroup> 
Problemi correlati