2

设置:Tomcat 上的 Resteasy + Spring Security。客户端/服务器之间交换的数据采用 JSON 格式。当应用程序抛出任何异常时,让异常映射器返回 JSON 格式的消息。

目标:每当出现问题时,始终从服务器返回格式正确的 JSON 错误消息。

发生了什么:Spring Security 层在 servlet 容器调用方法 foo() 之前被调用。如果这一层失败(例如错误的用户 id),甚至在调用 servlet 之前就会抛出异常,因此错误的格式不正确。知道如何解决这个问题并在这种情况下返回 JSON 错误吗?

谢谢。

我的 web.xml 的一部分如果有帮助的话:

<filter>
    <filter-name>securityPropagationFilter</filter-name>
    <filter-class>com.foo.bar.context.servlet.SecurityContextPropagationFilter</filter-class>
</filter>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter>
    <filter-name>loggingFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>securityPropagationFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
    <filter-name>loggingFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

<listener>
    <listener-class>
        org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
    </listener-class>
</listener>

<servlet>
    <servlet-name>
        Resteasy
    </servlet-name>
    <servlet-class>
        org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
    </servlet-class>
</servlet>
4

2 回答 2

1

我通过将以下内容添加到我的 web.xml 来解决这个问题

<error-page>
    <error-code>403</error-code>
    <location>403.json</location>
</error-page>

另一方面,对于需要处理的每个错误代码,我都需要一个条目。但我想如果我也必须在 Spring 中调整异常处理程序,我也必须这样做。

于 2011-03-04T22:02:22.030 回答
0

我将不得不更深入地挖掘,但您可以使用 RESTeasy 或 Spring 中的异常映射器来解决这个问题。

于 2011-01-24T19:04:20.807 回答