Search code examples
javavalidationstrutsstruts-1

How do I check ActionErrors for a specific error?


I'm writing a custom ActionErrors message for our application, to display a particular error for a specific circumstance.

public class ErrorForm  extends ActionForm{
public ActionErrors validateForm(ActionMapping mapping, HttpServletRequest request){
errs.add(FORM_KEY_ACTION_TYPE, new ActionMessage(WebGlobals.CUSTOM_ERROR));
return errs;
}
}

Unfortunately, the way our code is structured (and I would rather not try to sell "let's restructure four classes for one small change), the ErrorForm is a parent to several other classes. And for reasons other than what I've shown in my code snippets, the validation has to be done in the ErrorForm class.

When the parent class terminates, and returns the ActionErrors to the child, the child class adds an error message of its own, as shown below.

public class ErrorThrowingForm extends ErrorForm {
public ActionErrors postValidate(ActionMapping mapping, HttpServletRequest request)
{
    ActionErrors errs = super.validateForm(mapping, request);

    if (errs.size() > 0)
    errs.add(WebGlobals.GENERAL_ERROR_KEY, new ActionMessage(WebGlobals.PROP_FIELD_ERROR));

return errs;
}
}

Despite the fact that the error message was returned from the parent class, only the child class's error message is displayed, and the parent's error message is never seen. The form field that throws the validation error displays a ! next to it, but the associated Custom_Error message does not display.

I want to return the custom error message. And I do not have the ability to just add that error in the children class.

How can I determine what errors are in my ActionErrors message, so that I can check for my Custom Error and return it, rather than depending on the children class?

I've already tried simply removing the entire "if" block and returning errs directly as they're received from the validateForm method, but when I do, the error message fails to display on the page, and I do not know why.


Solution

  • The parent form should be a child of ValidatorForm in your terms, that you should better understand. In the child form of your parent you should add validate method to invoke validation. Then in the parent implementation you should call framework's super method at the first statement preferably, then you can add error messages to ActionErrors returned by the framework. Hope you understand this.

    public class ErrorForm  extends ValidatorForm{
    public ActionErrors validateForm(ActionMapping mapping, HttpServletRequest request){
    ActionErrors errs= super.validate(mapping, request); 
    errs.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage(WebGlobals.CUSTOM_ERROR));
    return errs;
    }
    }