Validating an Action with a method other than execute

One of the useful features of Struts2 is that the method in your Action that you want the framework to execute does not have to be called execute. While this doesn’t sound like much it means that you can re-use the majority of an Action without having to go down the route of inheriting from a base class.

Following up from my previous post of unit testing actions with annotation based validation, someone asked me how you can specify validation on a method other than action, and here’s how.

Re-using the SimpleAnnotatedAction we rename the execute to something else.


public class SimpleAnnotatedAction extends ActionSupport {

    private String name;

    public String notExecute() {
        return Action.SUCCESS;
    }

    public String getName() {
        return name;
    }

    @RequiredStringValidator(message = "Please specify a simple name")
    public void setName(String name) {
        this.name = name;
    }
}

And validating it just means adding the name of the method to the validate() method of the ActionValidationManager.


    @Test
    public void shouldTestSimpleAnnotationBasedValidation() throws ValidationException {
        SimpleAnnotatedAction action = new SimpleAnnotatedAction();

        avm.validate(action, "", "notExecute");
        assertTrue(action.getFieldErrors().size() > 0);
        assertEquals("Please specify a simple name",
                      action.getFieldErrors().get("name").get(0));
    }