Struts 2 how to run a validation before every action

803 views Asked by At

In a Struts 2 application, I want to run a logic before all project actions. The logic will generate a field error or let the action continue.

I tried to develop an interceptor for this case.

But here is my problem:

In a validator we call addFieldError(fieldName, object); to set field error, but I don't know how can I add field errors in an interceptor.


If that is not possible, please let me know if I can use a validator which runs before all my actions ( I use @Validations, and I am looking for a way not to copy a my validator on top of all my actions! )

2

There are 2 answers

0
binoternary On BEST ANSWER

You can add field (and action) errors by casting the action invocation to ValidationAware in your interceptor. Obviously your action has to actually implement the ValidationAware interface, but it probaly does (e.g if your action extends ActionSupport then it's also ValidationAware because ActionSupport implements ValidationAware):

public String intercept(ActionInvocation invocation) throws Exception {
    Object action = invocation.getAction();
    if (action instanceof ValidationAware) {
        ValidationAware validationAware = (ValidationAware) action;
        validationAware.addFieldError("field", "field error");
        validationAware.addActionMessage("action message");
        validationAware.addActionError("action error");
    }
    return invocation.invoke();
}
0
Andrea Ligios On

You can call addFieldError() on the action simply casting it to the ValidationAware interface:

public String intercept(ActionInvocation invocation) throws Exception {
    ActionContext invocationContext = invocation.getInvocationContext();
    Object action = invocation.getAction();

    if (action instanceof ValidationAware) {
        ValidationAware va = (ValidationAware) action;
        va.addFieldError("field", "message");
    }

    ....
}