0

I am building a JSF2 application with multi-lingual content.

1) Bean validation will be used for validating the form fields. I use ValidationMessages properties files to define locale specific error messages and use the <h:message> tag for displaying the correct error message on screen.

2) For application specific exceptions, I currently have a generic ApplicationException which is handled in managed bean methods. Inside the exception catch block, I set a "msg" field in the bean with a custom error message (For e.g: "The inventory cannot be updated as no matching product code found"). In the xhtml pages, I check if the "msg" string is not empty and display it on top of the page.

Is there a better way to handle display of success and error messages in JSF? Can I simply throw the ApplicationException in managed beans and have a generic handler to handle the exceptions and display messages in the relevant view? I read https://weblogs.java.net/blog/edburns/archive/2009/09/03/dealing-gracefully-viewexpiredexception-jsf2, but I am not able to map it to my requirement

Raj
  • 45
  • 1
  • 5

1 Answers1

0

You're doing it almost properly. The way for the component validations is the one to go. However, for your managed bean logic, it's not necessary to implement a custom String property in your bean. Just add the message you want in your action method and it will be displayed by the h:messages tag:

FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, 
    "The inventory cannot be updated as no matching product code found","");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, message);

Using an ExceptionHandler for just displaying a message seems overcomplicated. It also won't work for asynchronous (Ajax) requests, unless you use a third party solution like Omnifaces.

See also:

Community
  • 1
  • 1
Aritz
  • 30,971
  • 16
  • 136
  • 217
  • Thanks @XtremeBiker. How can I handle localization while setting messages in FacesContext? Should I define a separate resource bundle for this? (apart from ValidationMessages and resource-bundle used in JSF pages)? – Raj Jul 30 '14 at 16:48
  • There's no need for that, you can access the resource bundle either using EL expression or the JSF API in the managed bean side. Have [a look](http://stackoverflow.com/a/6272972/1199132). – Aritz Jul 30 '14 at 16:52