JSF格式的IF-ELSE条件.需要知道正确的方法

问题描述:

我的表单上有if-else条件,其中显示标题和用于添加和更新的按钮文本.

There is if-else condition on my form where I show heading and button text for add and update.

下面的代码是我在struts2项目中使用的代码,而相同的代码想在xhtml页面的JSF2项目中使用.

Below code what I have used in struts2 project and same code want to use in JSF2 project in xhtml page.

Struts2页面

 <s:if test="person==null || person.id==null || person.id==''">
                <s:set var="buttonText" value="getText('person.button.add')"/>
                <s:text name="person.h1.add.text"/>
                <i><s:text name="person.smallfont.add.text"/></i>
            </s:if>
            <s:else>
                <s:set var="buttonText" value="getText('person.button.edit')"/>
                <s:text name="person.h1.edit.text"/>
                <s:text name="person.smallfont.edit.text"/>
            </s:else>

我可以在xhtml页面中使用JSTL并按原样使用上面的代码,但是我看到了不同的方法,例如下面的使用EL.我不确定但不喜欢下面的方法

I could use JSTL in xhtml page and use above code as it is but I saw different approaches for this like below using EL. I am not sure but don't like below approach

<h:outputLabel value="Add Information" rendered="#{!empty personBean.person.id}" />
<h:outputLabel value="Use the form below to add your information." rendered="#{!empty personBean.person.id}" />

<h:outputLabel value="Update Information" rendered="#{empty personBean.person.id}" />
<h:outputLabel value="Use the form below to edit your information." rendered="#{empty personBean.person.id}" />

我的问题:

请有人指导我如何在JSF项目的IF-ELSE条件下使用以上代码.使用EL/JSTL还是其他?

实际上只是使用rendered属性.如有必要,您可以将其包装在根本不发出任何HTML的另一个组件中,例如<h:panelGroup><ui:fragment>,这样就无需在所有后续组件上重复相同的rendered条件. /p>

Indeed just use the rendered attribute. You can if necessary wrap it in another component which doesn't emit any HTML at all, such as <h:panelGroup> or <ui:fragment>, so that you don't need to repeat the same rendered condition over all subsequent components.

<h:panelGroup rendered="#{not empty personBean.person.id}">
    Add Information
    <i>Use the form below to add your information.</i>
</h:panelGroup>
<h:panelGroup rendered="#{empty personBean.person.id}">
    Update Information
    <i>Use the form below to edit your information.</i>
</h:panelGroup>

请注意,<h:outputLabel>会生成HTML <label>元素,该元素在语义上与您最初拥有的<s:text>完全不同.您可能想使用<h:outputText>代替或完全省略它. JSF2/Facelets仅支持纯文本,甚至还支持模板文本中的EL,而无需<h:outputText>.

Please note that <h:outputLabel> produces a HTML <label> element which has semantically a completely different meaning than the <s:text> which you initially have. You perhaps want to use <h:outputText> instead or just omit it altogether. JSF2/Facelets just supports plain text and even EL in template text without the need for <h:outputText>.