如何在 jsf 2 中显示消息?

How to show message in jsf 2?

在 login.xhml 页面我有这个代码:

<h:inputText id="it1" value="#{requestScope.bestGuess}"/>
<p />
<h:message for="it1" />
<p />
<h:commandButton value="try" id="cb1" actionListener="#   {LoginBean.verifyAnswer}" Submit="true" immediate="false"/>

LoginBean 中的这段代码:

public class LoginBean {
    public void verifyAnswer(ActionEvent actionEvent) {
        FacesContext fctx = FacesContext.getCurrentInstance();
        ExternalContext ectx =  fctx.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) ectx.getRequest();
        Captcha captcha = (Captcha) ectx.getSessionMap().get(Captcha.NAME);
        try {
          request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
          //bad luck - but ignore
          System.out.println("UTF not supported !");
        }
        String answer = (String) ectx.getRequestMap().get("bestGuess");
        if (answer != null && captcha.isCorrect(answer)){
          /*message("Hello, Human");*/
          fctx.addMessage("it1",new FacesMessage("Hello, Human"));
        }
        else{
          /*message("Hello Mr. Roboto. Try again.");*/
          fctx.addMessage("it1",new FacesMessage("Hello Mr. Roboto. Try again."));
        }
      }  
}

cpatcha时如何显示消息? 例如:cpatcha true show "Hello, Human" 或 cpatcha false show "Hello Mr. Roboto. Try again."

我认为您必须更改 bean 中消息的规范,您需要指定表单和消息标记,尝试更改 bean 中的这段代码:

fctx.addMessage("it1",new FacesMessage("Hello Mr. Roboto. Try again."));

具有以下内容:

fctx.addMessage("yourForm:it1",new FacesMessage("Hello Mr. Roboto. Try again."));

使用 yourForm 作为表单的 ID。