我正在尝试返回一个 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/