【问题标题】:Spring Error: only capable of generating responses with characteristics not acceptable according to the request "accept" headersSpring 错误:仅能够根据请求“接受”标头生成具有不可接受特征的响应
【发布时间】:2015-11-06 03:07:43
【问题描述】:

我正在使用 spring 构建一个 Restful API,当我访问以下方法时:

// get the entity in DB by using id number
    @RequestMapping(value = "/{id:.+}", method = RequestMethod.GET)
    public @ResponseBody
    User getEmployee(@PathVariable("id") String email) {
        User user=null;
        System.out.println(email);
        try {
            user = dataServices.getEntityById(email);

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(user.getNickname());
        return user;
    }

使用此网址:http://localhost:8080/RestCrud/user/richard_johnson@sina.com

收到 406 错误:

我确定我已经添加了

<mvc:annotation-driven />

在我的 spring-config.xml 中。

我也确定我在 pom.xml 中添加了这些 jackson 依赖项

************************编辑****************************** ***********

************************再次编辑****************************** ******

如您所见,我没有在 @RequestMapping 注释中限制标头,因此我认为这不是与标头限制相关的问题。

另外,我的网址格式如下:

http://localhost:8080/RestCrud/user/id

我已经测试了“列表” http://localhost:8080/RestCrud/user/list

它可以工作,但“id”路径不起作用

【问题讨论】:

  • 你有什么问题?
  • 嗯,请求来自哪里?什么是请求接受标头?原因可能在那里......
  • 我的问题是如何解决这个 406 ;)
  • 嗨,谢尔盖我根据你的问题编辑了我的帖子

标签: java spring maven spring-mvc


【解决方案1】:

您似乎已经注释掉了一些杰克逊依赖项 发生错误是因为您的员工对象无法转换为浏览器可接受的格式。你肯定会想用 json 来回应。

Spring 4 需要以下 jackson 库

  • 杰克逊核心
  • 杰克逊核心萨尔
  • jackson-mapper-asl
  • 杰克逊数据绑定

更新:

查看您的 URL 模式,*.com 扩展正在推动 spring 执行内容协商,而不是验证接受标头。

您可以使用

强制 spring 不进行基于路径扩展的内容协商
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false" />
</bean>

【讨论】:

  • 嗨 Jozzy 我编辑了帖子,即使我添加了这些依赖项,仍然无法正常工作
【解决方案2】:

查看at this answer,简而言之,如果您使用的是 Spring 4,请确保包含 jackson-corejackson-databind 依赖项

【讨论】:

  • 嗨,我编辑了帖子,即使我添加了这些依赖项,仍然无法正常工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-24
  • 2023-03-15
  • 2017-05-27
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
相关资源
最近更新 更多