如何验证使用Struts2 Json插件发送的JSON而不抛出异常 [英] How to validate JSON being sent using Struts2 Json Plugin without throwing exception

查看:268
本文介绍了如何验证使用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 ,其中根据这里的插件源代码很好 - https://github.com/apache/struts2/blob/STRUTS_2_3_15_X/plugins/json/src/main/java/org/apache/struts2/json/JSONPopulator.java

Then the action throws a NumberFormatException, which is fine according to the plugin source code here - https://github.com/apache/struts2/blob/STRUTS_2_3_15_X/plugins/json/src/main/java/org/apache/struts2/json/JSONPopulator.java

但是插件中没有处理这个异常,因此从动作抛出异常返回,导致全局异常的触发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 。那么,我怎样才能使json-plugin以相同的方式返回 INPUT 并设置适当的 fieldErrors 而不是抛出 NumberFormatException 并触发 globalExceptionHandler

If the same request was sent using a query-string, ?dblField= then the action returns INPUT. 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?

推荐答案

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

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.

这篇关于如何验证使用Struts2 Json插件发送的JSON而不抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆