9.6. Formatting Error Messages

Problem

Your application requires a custom look and feel for error messages beyond the abilities of the html:errors tag.

Solution

Use the logic:messagesPresent and the html:messages tags to display the error messages in a custom format. The JSP fragment (errors.inc.jsp) shown in Example 9-11 can be included on any page that may need to display errors.

Example 9-11. Custom error display

<logic:messagesPresent>
<table border="1" bgcolor="orange" width="100%" align="center">
    <tr><td>
        <p>
            <img src="/images/icon-warning.gif" border="0"
              vspace="2" hspace="10" align="center">
            WARNING: <bean:message key="errors.heading"/>
        </p>    
        <ul>
            <html:messages id="error">
                <li><bean:write name="error"/></li>
            </html:messages>
        </ul>
    </td></tr>
</table>
<p>
</logic:messagesPresent>

Tip

The images used in the examples are included with the online source.

Discussion

Errors displayed using the JSP code in Example 9-11 result in a display similar to Figure 9-5.

Custom formatted errors

Figure 9-5. Custom formatted errors

Though the html:errors tag is a convenient way of displaying error messages, it's fairly restrictive in its formatting. By default, it displays all errors for a page, starting with a header markup, then each error message, and ending with footer markup.

Tip

Using the property attribute, you can tell the html:errors tag to display error messages for a specific field. This ability is commonly used to display ...

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.