2012-02-19 60 views
2

我有一个简单的表单,获取代码然后显示他的libelle,我添加了一个验证bean,检查代码是否存在。 我的问题是我不能显示代码不存在时的错误消息。inputText验证程序不显示错误消息

下面是代码:

test.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" 
     xmlns:h="http://java.sun.com/jsf/html" 
     xmlns:f="http://java.sun.com/jsf/core"> 
<h:head><title>Test</title> 
</h:head> 
<body class="bodyMain"> 

<h:form>   
    <h:panelGrid columns="3"> 
     <h:outputText value="Code: " /> 
     <h:inputText id="code" value="#{myBean.code}" 
      validator="#{myBean.validateCode}"> 
      <f:ajax execute="@this" render="libelle" listener="#{myBean.setLibelle()}"/> 
     </h:inputText> 
     <h:message for="code" style="color:red"/> 
    </h:panelGrid> 
    <h:panelGrid id="libelle" columns="2"> 
     <h:outputText value="Libelle: " /> 
     <h:outputText value="#{myBean.libelle}" /> 
    </h:panelGrid> 
</h:form>  

</body> 
</html> 

MyBean.java

@ManagedBean 
@ViewScoped 
public class MyBean implements java.io.Serializable{ 
    private static final long serialVersionUID = 1L; 

    private String code=""; 
    private String libelle=""; 

    public String getCode() { 
     return this.code; 
    } 

    public void setCode(String code) { 
     this.code=code; 
    }  

    public String getLibelle() { 
     return this.libelle; 
    } 

    public void setLibelle(String libelle) { 
     this.libelle=libelle; 
    } 

    public void setLibelle() { 
     if (code.compareTo("1")==0) 
      libelle="One"; 
     else 
      libelle=""; 
    } 

    public void validateCode(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException { 
     String code = (String)value; 
     if (code.compareTo("1") != 0) { 
      FacesMessage message = new FacesMessage("Code doesn't exist"); 
      throw new ValidatorException(message); 
     } 
    } 

} 

感谢你的帮助,以解决此问题

回答

3

你不通过<f:ajax>更新<h:message>组件。您需要给<h:message>一个id并将其包含在<f:ajax render>中。

<h:inputText id="code" value="#{myBean.code}" validator="#{myBean.validateCode}"> 
    <f:ajax execute="@this" render="libelle codeMessage" listener="#{myBean.setLibelle()}"/> 
</h:inputText> 
<h:message id="codeMessage" for="code" style="color:red"/> 

无关到具体问题,不初始化属性为空字符串。让他们默认null。另外,比较对象应该使用equals()方法,而不是使用compareTo()。最后,使用包含所有可用值而不是输入字段的下拉列表将更加便于用户使用。

+0

它工作正常,非常感谢。 – 2012-02-20 09:45:48

+0

不客气。 – BalusC 2012-02-20 13:36:49