如果没有用户输入则隐藏 h:outputText 元素

Hide h:outputText element if there was no user input

<h:form id="aform">

    <p:growl id="debug-growl" showDetail="true" sticky="false" />

    <p:inputText id="expression" value="#{debug.expression}" required ="true" />

    <p:commandButton update="debug-growl" value="Process" action="#{debug.myaction}" />

    <h:outputText value="Source regular expression: #{debug.expression}" rendered="#{not empty debug.expression}" />

</h:form>

豆子

@ManagedBean
@ViewScoped
public class Debug implements Serializable {

    private String expression; //getter & setter is present

当我输入值时,它会在 h:outputText 元素中提交后显示。 但是如果我输入空值(这是错误的),那么在 h:outputText 元素中仍然存在以前的值。

如何在未提交任何值时隐藏 'h:outputText'?

所以我发现上面的代码有 2 个问题。

  1. 您没有更新命令按钮单击上的 h:outputText。您需要向 h:outputText 添加一个 ID,并将其作为更新添加到命令按钮

    <p:commandButton update="debug-growl someText" value="Process" action="#{debug.myaction}" />
    
    <h:outputText id = "someText" value="Source regular expression: #{debug.expression}" rendered="#{not empty debug.expression}" />
    
  2. inputText 上要求的="true" 不允许将空值提交给服务器。因此 h:outputText 永远不会为空,因此这个值将始终被渲染。要解决此问题,我会在服务器上进行验证。

    JSF

    删除所需的="true" 标签

    <p:inputText id="expression" value="#{debug.expression}"/>
    

    Java

    public void myAction(){
    
        //check to make sure inputText isnt null/blank first
        if(StringUtils.isBlank(expression))
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Error", "Must provide value"));
        else{
             //business logic
        }
    }