Struts中的Json插件和全局异常

时间:2018-04-03 22:12:47

标签: java struts2 struts2-json-plugin

我正在尝试返回JSON格式的全局异常。这是我目前的struts.xml。我不确定我错过了什么。

<struts>

<constant name="struts.devMode" value="true" />
<constant name="struts.custom.i18n.resources" value="global" />
<constant name="struts.configuration.xml.reload" value="true" />

<package name="mkaStrive" extends="json-default">
    <interceptors>
        <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor" />
        <interceptor-stack name="mobileStack">
            <interceptor-ref name="json" />
            <interceptor-ref name="defaultStack" />
        </interceptor-stack>
    </interceptors>
    <default-interceptor-ref name="test" />

    <global-results>

        <!-- Exceptions are handled by ExceptionAction -->
        <result name="exception" type="chain">
            <param name="actionName">exception</param>
        </result>

    </global-results>

    <global-exception-mappings>
        <exception-mapping exception="java.lang.Throwable" result="exception" />
    </global-exception-mappings>

    <action name="exception" class="n.a.exception.ExceptionAction" />

    <action name="getQuestionsList" class="n.a.mkastrive.action.GetQuestions" method="execute">
        <interceptor-ref name="json" />
        <result type="json"></result>
    </action>       
</package>

我现在的GetQuestions操作只会抛出异常:

public String execute() throws Exception {
    throw new Exception("TEST");
}

从理想情况下,它应该看到我有全局结果,然后链接到名为exception的动作。

1 个答案:

答案 0 :(得分:1)

我在您提供的struts.xml中看到的唯一问题如下:(错字?)

使用

<default-interceptor-ref name="mobileStack" />

而不是

<default-interceptor-ref name="test" />

有了这个,您可以验证控件是否属于execute类的exception action方法:n.a.exception.ExceptionAction

现在,如果您要返回自定义抛出异常的响应,则可以包含json结果:

<action name="exception" class="n.a.exception.ExceptionAction" >
  <result type="json"></result>
</action>

为了获取从GetQuestions.execute()抛出的Exception实例,您可以在异常操作的execute方法中使用以下内容:

(Exception)ActionContext.getContext().getValueStack().findValue("exception");

您可以对此进行操作并在类中设置必需的私有字段,以便通过公共getter可用于json渲染。只需链接到tutorial以获取json响应。

相关问题