You have seen the errors tag in action in the previous chapters. Now it is time to take a closer look.
The errors tag is used to display error messages, especially those produced by an action form’s validate method. Understanding it will enable you to make full use this tag.
Like other custom tags, the errors tag communicates with the Struts action servlet through scoped objects. This means, for error messages to be displayed by the errors tag, they must be encapsulated in a scoped object. The errors tag was designed to locate the request-scoped object referenced by a scoped variable having a predefined name, which must be the same as the value of the ERROR_KEY field of the org.apache.struts.Globals class. The value of this field itself is not important.
To support the errors tag, the Struts action servlet stores the ActionErrors object returned by an action form’s validate method in the current HttpServletRequest object, using this code.
ActionErrors actionErrors = actionForm.validate(); request.setAttribute(Globals.ERROR_KEY, actionErrors);
What does the errors tag do with the ActionErrors object it retrieves? First of all, note that the errors tag has access to any .properties file you registered in the struts-config.xml file using the message-resources tag. Also note that the ActionErrors object that the errors tag has access to contains zero or many ActionMessage object. Each ActionMessage object contains a key and zero or more values and you add an ActionMessage object using this code:
errors.add("someString", new ActionMessage(key));
The key in the each ActionMessage will be used to look up a value in the registered properties file. If a value is found, the value (which is a message) is displayed.
For better formatting, the errors tag also looks for the following keys in the properties file:
For instance, for the following entries in a registered properties file.
errors.header=<table> errors.footer=</table> errors.prefix=<tr><td> errors.suffix=</td></tr>
the output of your errors tag would be
<table> <tr><td>error message 1</td></tr> ... <tr><td>error message n</td></tr> </table>
Thus, formatting the error messages as table rows. The errors tag automatically supports internationalization thanks to the message-resources tag that loads the correct localized properties file.