简体   繁体   English

Struts 2如何在执行每个操作之前运行验证

[英]Struts 2 how to run a validation before every action

In a Struts 2 application, I want to run a logic before all project actions. 在Struts 2应用程序中,我想在所有项目操作之前运行逻辑。 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); 在验证器中,我们称为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! ) 如果无法做到这一点,请让我知道我是否可以使用在所有操作之前运行的验证程序(我使用@Validations ,并且我正在寻找一种不将验证程序复制到所有操作之上的方法!)

You can add field (and action) errors by casting the action invocation to ValidationAware in your interceptor. 您可以通过将动作调用转换为拦截器中的ValidationAware来添加字段(和动作)错误。 Obviously your action has to actually implement the ValidationAware interface, but it probaly does (eg if your action extends ActionSupport then it's also ValidationAware because ActionSupport implements ValidationAware ): 显然,您的操作必须实际实现ValidationAware接口,但是它可能会这样做(例如,如果您的操作扩展了ActionSupport那么它也是ValidationAware因为ActionSupport实现了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();
}

You can call addFieldError() on the action simply casting it to the ValidationAware interface: 您可以在操作上调用addFieldError() ,只需将其强制转换为ValidationAware接口即可:

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");
    }

    ....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM