java - Struts 中的 Json 插件和全局异常

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

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

最佳答案

我在 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() 抛出的异常实例,您可以在异常操作的 execute 中使用以下内容方法:

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

您可以对此进行操作并在类中设置所需的私有(private)字段,以便它们可以通过公共(public) getter 用于 json 渲染。只是链接到 tutorial用于 json 响应。

关于java - Struts 中的 Json 插件和全局异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49639883/

相关文章:

java - Lucene 不同的结果

java - 封装类和使类更安全之间的区别

javascript - 无法访问 Action 类中禁用下拉列表的所选项目的值(struts 2)

java - Struts 2 JSON插件和通配符问题

java - 我们如何将 Struts2 操作类传递给 angularjs $http get

java - 没有为使用 Struts 2 jQuery Grid 映射到名称 'json' 的类型 'success' 定义结果类型

java - 在目录android中保存图像时出现空指针异常

java - 如何在Tomcat5.5中上传文件?

java - Websphere : ClassCastException for Webservice

java - Struts2 文本域显示长度