Json Struts 中的插件和全局异常

Json Plugin and Global exception in Struts

我正在尝试 return 一个 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");
}

理想情况下,它应该从这里看到我有全局结果,然后链接到名为异常的操作。

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

使用

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

而不是

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

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

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

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

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

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

您可以对此进行操作并在 class 中设置所需的私有字段,以便它们可通过 public 吸气剂用于 json 呈现。只需链接到 tutorial 以获得 json 响应。