【问题标题】:Spring json 406 statusSpring json 406 状态
【发布时间】:2014-07-17 07:07:15
【问题描述】:

我已将 jackson 的 jars 添加到我项目的 lib 目录 jackson-core-asljackson-mapper-asl。我还在 dispatcher-servlet.xml 中写了以下内容:

<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageConverter"/>
        </list>
    </property>
</bean>

我的控制器是:

@Controller
public class SaleController {
@RequestMapping(value = "/sales/info", produces = "application/json", headers = "Accept=*/*")
    public @ResponseBody Product getProductJson(@RequestParam String id) throws SQLException
    {
        ProductDAO mapping = new ProductDAOImpl();
        Product product = mapping.getProductById(Integer.parseInt(id));
        return product;
    }
}

但是当我尝试在浏览器中获取此响应时,我仍然收到 406 HTTP status message 而不是 JSON 响应。

注意在您将我的帖子标记为重复之前,我检查了thisthisthis,但它没有没用。

【问题讨论】:

  • 首先检查您是否使用Content-Type: application/json 标头发送,然后从@RequestMapping 中删除headers 属性,看看是否可行。
  • 您使用了请求映射中未定义的请求参数id
  • @Bart 如何使用 Content-Type: application/json 发送?
  • @DmitryFucintv 我的错。我看到你只回复 JSON :-) 不确定你使用的是哪个 Spring MVC 版本,但你通常不需要为 Jackson 声明消息转换器。春天会自己捡起来。尽可能使用 Jackson 2+。

标签: java json spring spring-mvc


【解决方案1】:

使用 Spring 3.2.2 版,无需注册任何自定义消息转换器

所以你的配置应该是这样的

<context:component-scan base-package="com.your.package.controller" />

<mvc:annotation-driven />

之后在你的 POM 文件中有这两个依赖项

<dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.2</version>
        </dependency>

您也可以尝试在 Accept 标头中添加应用程序/json

【讨论】:

    猜你喜欢
    • 2014-02-09
    • 1970-01-01
    • 2011-06-26
    • 2015-11-20
    • 2020-11-27
    • 2019-04-30
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多