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! )
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();
}