【问题标题】:I want my controlleradvice to always produce JSON when handling exceptions我希望我的 controlleradvice 在处理异常时始终生成 JSON
【发布时间】:2014-09-10 20:27:04
【问题描述】:

我已将我的休息服务的异常处理集中到一个简洁的 ControllerAdvice 中。

我正在返回常规传输对象,希望我很酷的 mapping-jackson-converter 将其转换为最终客户端的 JSON。

现在是这样。如果我没有将 accept-header 设置为“Application/JSON”,我不会得到转换后的 JSON,而是在我的测试中得到一些默认的 HTML,这似乎是由 Jetty 生成的。我不得不承认我不确定为什么,但我想这是一些默认的 Spring 解析器生效。

这让我开始思考。调用我的 rest URL 的客户应该知道我返回 JSON,所以我希望我的服务始终返回 json。

有没有办法将 ReqeustMappingHandlerAdapter 配置为始终生成 JSON?

我当前的配置:

<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <beans:property name="messageConverters">
        <beans:list>
            <beans:ref bean="jsonConverter"/>
        </beans:list>
    </beans:property>
</beans:bean>

<!-- Instantiation of the converter  in order to configure it -->
<beans:bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <!--beans:property name="supportedMediaTypes" value="application/json"/-->
</beans:bean>

【问题讨论】:

  • 你能发布你的方法异常处理程序定义吗?
  • 我只有一个@controlleradvice 类,就像这个例子中的petrikainulainen.net/programming/spring-framework/…
  • 你的方法有@ResponseBody注解吗?
  • 确实如此。正如我所提到的,如果我将接受标头设置为 json,它会起作用,如果我删除它,它会默认为一些生成的 HTML。我希望它始终只生成 JSON。

标签: json spring rest spring-mvc


【解决方案1】:

我不知道这是否能回答您的问题,但您可以将 Spring 配置中的默认内容类型设置为 JSON(在 Spring MVC 中默认为没有 Accept 标头的 HTML)。这是一个示例配置:

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="defaultContentType" value="application/json" />
</bean>

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />

来源:

http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

【讨论】:

  • 谢谢。这不是一个坏主意,但不适用于我的应用程序,因为我有 JSON 和 Html 客户端。
猜你喜欢
  • 2018-07-13
  • 2022-10-14
  • 2014-08-26
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 2020-12-02
  • 2019-06-04
相关资源
最近更新 更多