Search code examples
jsferror-handlingfacelets

How to display my application's errors in JSF?


In my JSF/Facelets app, here's a simplified version of part of my form:

<h:form id="myform">
  <h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" />
  <h:message class="error" for="newPassword1" />
  <h:inputSecret value="#{createNewPassword.newPassword2}" id="newPassword2" />
  <h:message class="error" for="newPassword2" />
  <h:commandButton value="Continue" action="#{createNewPassword.continueButton}" />
</h:form>

I'd like to be able to assign an error to a specific h:message tag based on something happening in the continueButton() method. Different errors need to be displayed for newPassword and newPassword2. A validator won't really work, because the method that will deliver results (from the DB) is run in the continueButton() method, and is too expensive to run twice.

I can't use the h:messages tag because the page has multiple places that I need to display different error messages. When I tried this, the page displayed duplicates of every message.

I tried this as a best guess, but no luck:

public Navigation continueButton() {
  ...
  expensiveMethod();
  if(...) {
    FacesContext.getCurrentInstance().addMessage("newPassword", new FacesMessage("Error: Your password is NOT strong enough."));
  }
}

What am I missing? Any help would be appreciated!


Solution

  • In case anyone was curious, I was able to figure this out based on all of your responses combined!

    This is in the Facelet:

    <h:form id="myform">
      <h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" />
      <h:message class="error" for="newPassword1" id="newPassword1Error" />
      <h:inputSecret value="#{createNewPassword.newPassword2}" id="newPassword2" />
      <h:message class="error" for="newPassword2" id="newPassword2Error" />
      <h:commandButton value="Continue" action="#{createNewPassword.continueButton}" />
    </h:form>
    

    This is in the continueButton() method:

    FacesContext.getCurrentInstance().addMessage("myForm:newPassword1", new FacesMessage(PASSWORDS_DONT_MATCH, PASSWORDS_DONT_MATCH));
    

    And it works! Thanks for the help!