Tuesday, July 26, 2005

Super annoying Struts error

So I've run into this a couple of times before and found it very frustrating. Hopefully this will help some people avoid that same frustration! Basically, you can display validation error messages in a Struts form page with this syntax:

   <html:messages id="errors" message="false">
      <bean:write name="errors"/>

Under some (previously mysterious to me) circumstances, this can give you this error message:

An unhandled exception occurred. The name of the exception is:
Cannot find bean errors in any scope
javax.servlet.jsp.JspException: Cannot find bean errors in any scope

The problem comes all the way back in your form or action class when you create the error message. Unfortunately, it's not at all related to the actual message. In fact, your bean is there! Or at least in my particular case it's there. So I do this in the action class (you can also get error messages from within the validate() method of your form class if you're subclassing the ValidatorForm class):

ActionMessages errors = new ActionMessages();

if (someBooleanErrorCondition)
              new ActionMessage("Here's your error message!");

if (!errors.isEmpty())
   saveErrors(request, errors);

Things go wrong at the point where I'm creating the new ActionMessage object. The problem is that I put the literal message in the constructor instead of a resource key from the ApplicationResources.properties file. Replace that line with:

           new ActionMessage("error.message.whatever");

If that was your problem, this should fix it.

No comments: