【问题标题】:Spring JSON and 406 HTTP errorSpring JSON 和 406 HTTP 错误
【发布时间】:2012-07-03 09:44:06
【问题描述】:

我发现很多关于这个问题的问题,但我没有解决...... 我有这个方法:

@RequestMapping(value="/testInit")
public @ResponseBody Output test() throws Exception {
    return new Output(true);
}

我有杰克逊库到类路径,进入 applicationContext 但我仍然得到这个 jquery 调用的 406 错误:

$.ajax({
    url: "/testInit",
    type: "get",
    dataType: "json"
}); 

【问题讨论】:

    标签: jquery json spring jackson


    【解决方案1】:

    您必须添加 jars 并添加 org.springframework.http.converter.json.MappingJacksonHttpMessageConverterorg.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter 到 DispatcherServlet-servlet.xml

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

    如上图所示。

    【讨论】:

      【解决方案2】:

      当客户端请求了服务器无法返回的内容类型时,使用406 Not Acceptable 响应。换句话说,您的客户端(例如 Web 浏览器)正在发送与服务器功能不匹配的 Accept 标头。

      我猜测 jQuery Ajax 方法在设置 Accept 标头时使用了 dataType 字段。 json 不是众所周知的内容类型,但 application/json 是。

      尝试将dataType: "json" 替换为dataType: "application/json"

      【讨论】:

      • 这是使用 firebug 捕获的标头:Accept application/json, text/javascript, /; q=0.01
      【解决方案3】:

      我使用 jackson-all.1.9.0.jar 而不是 jackson 2 库解决了问题。

      【讨论】:

        【解决方案4】:

        我可以让我的工作的唯一方法是将 spring 升级到 3.1 并将生产添加到请求映射。

        @RequestMapping(value = "/rest/{myVar}", method = RequestMethod.GET, produces = "application/json")
        @ResponseBody
        public MyObject get(
                @PathVariable String myVar) {
        

        其他解决方案都不适合我

        【讨论】:

          【解决方案5】:

          我遇到了这个问题,最后追查到我正在使用的类上没有任何吸气剂。

          即这导致了 406

          public static class Pojo {
              private int x;
              public Pojo(int x) {
                  this.x = x;
              }
          }
          

          但这并没有

          public static class Pojo {
              private int x;
              public Pojo(int x) {
                  this.x = x;
              }
              public int getX() {
                  return x;
              }
          }
          

          是的,我正在使用一个名为 Pojo 的类 :) - 我只是在做一个虚拟示例来检查 Jackson 是否在我的新设置中工作

          【讨论】:

            猜你喜欢
            • 2015-03-17
            • 1970-01-01
            • 2018-01-23
            • 1970-01-01
            • 2014-02-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-06-26
            相关资源
            最近更新 更多