tags:

views:

784

answers:

2

Hi all, I am learning JSF and came across this line:

<h:messages layout="table"></h:messages>

in a sample application ?

Am not sure what does this line do? I get no error when removing the line from the code, and am able to run it and get the same output ?

+3  A: 

The components <h:message> and <h:messages> are dedicated to display messages to users (generally error message).

For example, when you have a validation on a field that failed (for example the user didn't fill a required field, or inputed a string in a number-only field), then a FacesMessage is added to the FacesContext object. The <h:message> and <h:messages> are then used to display the message in the page.

The component <h:messages> will display all the messages contained in the FacesContext, while the <h:message> is dedicated to a specific clientId (a specific field). The latter is usefull when you want to place the message close to a field for example.

Note that you can add any kind of message that will displayed to the user:

FacesContext.getInstance().addMessage(null, new FacesMessage("The message to display"));

In this example, the first parameter is the ID field of the field that is concerned by this message (usefull when the message is a validation message for a specific field). null means that the message is a general information (i.e. not linked to any particular field).

You can see an example of this component here. Note that this example uses the rich:messages that is an extension (provided by RichFaces) of the "basic" <h:message/>, but the principle is the same.

romaintaz
+5  A: 

The h:messages tag renders all messages for the current JSF view which are not covered by a h:message (remark the missing 's' at the end) tag. Messages can be generated explicitly by your backing beans (FacesContext.addMessage) or implicitly by JSF.

E.g. if you have marked an input value as required and the user submits the form without filling in the required value, an error message will be added to the view. If a h:message tag is bound to the relevant component, the message will be rendered there, otherwise it will be rendered by the global h:messages tag in your view (if any).

The layout attribute specifies how the HTML code to be generated should look like. The table layout (used in your example) uses an HTML table to display messages, while the list layout uses a bulleted list (HTML ul tag).

If you do not specify a h:messages tag in your view and also no h:message tags, the user will not be informed about errors. Therefor it is best practice to include a h:message tag for each input component of your view and a h:messages tag for your whole view, to ensure, that all messages are visible to the user.

You will find a compact JSF tag reference at JSF Toolbox.

sven