如何验证使用 Struts2 JSON 插件发送的 JSON 而不抛出异常

假设动作中有一个 Double 变量,如果请求正文中发送的值类似于

Suppose there's a Double variable in an action, and if the value sent in the request body is something like

{"dblField":""}

interceptorStack 看起来像:

<action name="save" class="actions.MyAction" method="save">
    <interceptor-ref name="jsonValidationWorkflowStack">
    </interceptor-ref>
    <!--<interceptor-ref name="loginStack"/>-->
   <!-- I've tried using each of the above two separately, but both failed -->
    <interceptor-ref name="json">
        <param name="enableSMD">true</param>
    </interceptor-ref>
    
    <result type="json" name="*">
        <param name="excludeProperties">
            idIo
        </param>
    </result>
</action>

然后动作抛出NumberFormatException,根据插件源代码这里.

Then the action throws a NumberFormatException, which is fine according to the plugin source code here.

但是这个异常并没有在插件中处理,因此,从动作抛出异常返回,这导致 global-exception-handler 的触发.

But this exception is not handled in the plugin and hence, returns from the action throwing exception, which results in the firing of global-exception-handler.

如果使用查询字符串发送相同的请求,?dblField= 则操作返回 INPUT.

If the same request was sent using a query-string, ?dblField= then the action returns INPUT.

那么,我怎样才能使 json-plugin 以相同的方式返回 INPUT 并设置适当的 fieldErrors 而不是抛出 NumberFormatException并触发 globalExceptionHandler?

So, how can I make the json-plugin behave in the same way to return INPUT and set appropriate fieldErrors instead of throwing NumberFormatException and firing the globalExceptionHandler?

推荐答案

你可以把 exception 拦截器 在你自己的拦截器之前而不是 json 拦截器 通过扩展 json 拦截器并覆盖 intercept 方法,您可以在其中捕获错误.然后,您可以添加操作错误或重新抛出自定义异常,您可以在操作配置中或全局映射.

You could place exception interceptor before your own interceptor instead of the json interceptor by extending json interceptor and override intercept method where you can catch errors. Then you can either add action errors or rethrow a custom exception which you can map in the action config or globally.

<exception-mapping exception="org.exceptionmapping.CustomException"
                             result="errorresult"/>

这样您可以将所有仅 json 的拦截器错误映射到您的自定义异常.

This way you can map all json only interceptor errors with your custom exception.

相关文章