【问题标题】:spring mvc not returning json content - error 406spring mvc 不返回 json 内容 - 错误 406
【发布时间】:2011-05-03 11:08:33
【问题描述】:

我正在使用 Spring MVC 和 Ajax Simplification Spring 3.0 article 中指定的 JSON。

根据各种论坛上的建议对我的代码进行了多次尝试和修改后,我的代码仍然无法正常工作。

我不断收到以下错误:(406)此请求标识的资源只能生成具有根据请求“接受”标头()不可接受的特征的响应。

我的 appconfig.xml 中有要求。

app-config.xml

    <context:component-scan base-package="org.ajaxjavadojo" />

    <!-- Configures Spring MVC -->
    <import resource="mvc-config.xml" />

mvc-config.xml

<mvc:annotation-driven />

<!-- Forwards requests to the "/" resource to the "index" view -->
<mvc:view-controller path="/" view-name="index"/>


<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
  <entry key="html" value="text/html"/>
  <entry key="json" value="application/json"/>
</map>
</property>
<property name="viewResolvers">
<list>
  <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
</list>
</property>

</bean>

这就是我的控制器所拥有的

@Controller
@RequestMapping (value = "/convert")
public class ConversionController {

  @RequestMapping(method=RequestMethod.GET)
  public String getConversionForm(){
    return "convertView";
  }

  @RequestMapping(value = "/working", headers="Accept=application/json", method=RequestMethod.GET)
  public @ResponseBody Conversion getConversion(){
    Conversion d = new Conversion("d");
    return d;
  }
}

jsp jquery 调用

  function convertToDecimal(){
    $.getJSON("convert/working", {key: "r"}, function(aConversion){
      alert("it worked.");
      $('#decimal').val(aConversion.input);
    });
  }

非常感谢您对这个问题的任何意见。 谢谢

【问题讨论】:

    标签: java jquery spring spring-mvc jackson


    【解决方案1】:

    要从@ResponseBody-annotated 方法返回 JSON 响应,您需要做两件事:

    @RequestMapping 中不需要 ContentNegotiatingViewResolverheaders

    【讨论】:

    • 我已删除 ContentNegotiatingViewResolver 和标头信息,但仍无法正常工作。当您在类路径上说时,这是否意味着我必须导入杰克逊的库?如果是这样,我将它们包括在内。
    • 那么你的问题中还有一个不清楚的地方:app-config.xml 与 DispatcherServlet 的 ...-servlet.xml 配置有什么关系?
    • 在 web.xml 中,我指定了 servlet,然后是 app-config.xml (contextConfigLocation):dispatcherorg。 springframework.web.servlet.DispatcherServletcontextConfigLocation/WEB-INF/app-config.xml1
    • 这是我的问题!我有杰克逊-映射器-lgpl。我需要将其更改为 artifactId jackson-mapper-lgpl。
    • 将杰克逊 json 映射器添加到我的 maven 依赖项对我来说是正确的解决方案 - 投票++
    【解决方案2】:

    尝试删除Accept 的标头限制,放置一个断点并查看实际值是多少。或者使用 FireBug 执行此操作。

    也可以看看this jquery issue

    【讨论】:

    • 非常感谢。根据文章,接受标头应设置为 /。所以我将请求映射更新为:@RequestMapping(value = "/working", headers="Accept=*/*", method=RequestMethod.GET) 现在它可以工作了:))
    【解决方案3】:

    正如 axtavt 所说,mvc:annotation-driven 和 jackson JSON mapper 就是您所需要的。我遵循了这一点,让我的应用程序在不更改任何代码的情况下从同一方法返回 JSON 和 XML 字符串,前提是您从控制器返回的对象中有 @XmlRootElement 和 @XmlElement。不同之处在于请求或标头中传递的接受参数。要返回 xml,来自浏览器的任何正常调用都会执行此操作,否则将接受作为 'application/xml' 传递。如果要返回 JSON,请在请求的接受参数中使用“应用程序/json”。

    如果你使用firefox,可以使用tamperdata,改变这个参数

    【讨论】:

      【解决方案4】:

      我也遇到了这个错误,在深入兔子洞进行调试时遇到了这个异常

      java.lang.IllegalArgumentException:属性“错误”的 getter 定义冲突:com.mycomp.model.OutputJsonModel#isError(0 params) vs com.mycomp.model.OutputJsonModel#getError(0 params)

      所以基本上在我的 java bean 中我有如下内容:

      private boolean isError;
      private ErrorModel error;
      
      public ErrorModel getError() {
      return error;
      }
      
      public void setError(ErrorModel error) {
      this.error = error;
      }
      public boolean isError() {
      return isError;
      }
      
      public void setError(boolean isError) {
      this.isError = isError;
      }
      

      将错误成员变量名称之一更改为其他名称可以解决问题。

      【讨论】:

      • 谢谢,您的回答让我意识到我忘记了 getter 和 setter 方法。
      • 我遇到了同样的问题。确保响应对象具有 getter 和 setter。
      【解决方案5】:

      问题与 jquery 无关。甚至错误都说这是服务器端问题。请确保类路径中存在以下 2 个 jar:-

      jackson-core-asl-1.9.X.jar jackson-mapper-asl-1.9.X.jar

      【讨论】:

      • 当我从 1.9.x jackson 切换到 2.x (fasterxml) 时,它的一个版本为我修复了它。我只导入了核心,但没有导入注释或数据绑定。我对删除接受选项不满意。
      【解决方案6】:

      org.springframework.http.converter.json.MappingJacksonHttpMessageConverterorg.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter 添加到 DispatcherServlet-servlet.xml。并使用

      在第二个中引用第一个
      <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>
      

      【讨论】:

      • 非常感谢,这对我有用!唯一的变化是将 MappingJacksonHttpMessageConverter 在您的 sn-p 中重命名为 MappingJackson2HttpMessageConverter,这是最新的春季版本 - 4.2.0.RELEASE
      【解决方案7】:

      @RequestMapping(... , produces = "application/json")代替@RequestMapping(...headers="Accept=application/json"...)

      【讨论】:

        【解决方案8】:

        使用 jQuery,您可以将 contentType 设置为所需的类型(此处为 application/json; charset=UTF-8')并在服务器端设置相同的标头。

        记住在测试时清除缓存。

        【讨论】:

          【解决方案9】:

          我也遇到了同样的问题,我下载了这个 [jar]: (http://www.java2s.com/Code/Jar/j/Downloadjacksonall190jar.htm)!并放置在 lib 文件夹中,该应用程序就像一个魅力:)

          【讨论】:

          • 超级...这为我提供了解决方案。
          【解决方案10】:

          我也有这个问题,你必须在你的配置xml中添加&lt;mvc:annotation-driven /&gt;

          <!-- Jackson -->
                  <dependency>
                      <groupId>com.fasterxml.jackson.core</groupId>
                      <artifactId>jackson-databind</artifactId>
                      <version>${jackson.databind-version}</version>
                  </dependency>
          

          在你的 pom.xml 中

          【讨论】:

            【解决方案11】:

            我在将 Spring 从 3.2.x 升级到 4.1.x 后遇到了这个问题。我通过将 Jackson 从 1.9.x 升级到 2.2.x (fasterxml) 来修复

             <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>2.2.3</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.2.3</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>2.2.3</version>
            </dependency>
            

            【讨论】:

            • 谢谢老兄,问题快把我逼疯了!
            【解决方案12】:

            参见my answer to a similar problem here,Spring MVC 解释 URI 的扩展并更改在幕后生成的预期 MIME 类型,因此生成 406。

            【讨论】:

              【解决方案13】:

              我使用了 java 配置,我得到了同样的错误。我错过了将@EnableWebMvc 添加到配置文件中。在我的 webconfig 文件中添加 @EnableWebMvc 后,此错误得到解决。

              从 Spring 控制器返回的对象也应该有适当的 getter 和 setter 方法。

              package com.raghu.dashboard.config;
              
              import org.springframework.context.annotation.Bean;
              import org.springframework.context.annotation.ComponentScan;
              import org.springframework.context.annotation.Configuration;
              import org.springframework.web.servlet.config.annotation.EnableWebMvc;
              import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
              import org.springframework.web.servlet.view.InternalResourceViewResolver;
              
              import com.raghu.dashboard.dao.ITaskDAO;
              import com.raghu.dashboard.dao.TaskDAOImpl;
              
              
                  @Configuration
                  @EnableWebMvc  //missed earlier...after adding this it works.no 406 error
                  @ComponentScan(basePackages = { "com.raghu.dashboard.api", "com.raghu.dashboard.dao" })
                  public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
              
                      protected Class<?>[] getRootConfigClasses() { return null;}
              
                      protected Class<?>[] getServletConfigClasses() {
                          return new Class[] { MongoConfiguration.class};
                      }
              
                      protected String[] getServletMappings() {
                          return new String[]{"*.htm"}; 
                      }
              
                      @Bean(name = "taskDao")
                      public ITaskDAO taskDao() {
                          return new TaskDAOImpl();
                      }
              
                      @Bean
                      public InternalResourceViewResolver getInternalResourceViewResolver() {
                          InternalResourceViewResolver resolver = new InternalResourceViewResolver();
                          resolver.setPrefix("/WEB-INF/pages/");
                          resolver.setSuffix(".jsp");
                          return resolver;
                      }
              
                  }
              

              AppInitializer.java

              package com.raghu.dashboard.config;
              
              import javax.servlet.ServletContext;
              import javax.servlet.ServletException;
              import javax.servlet.ServletRegistration;
              
              import org.springframework.web.WebApplicationInitializer;
              import org.springframework.web.context.ContextLoaderListener;
              import org.springframework.web.context.WebApplicationContext;
              import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
              import org.springframework.web.servlet.DispatcherServlet;
                  public class AppInitalizer implements WebApplicationInitializer {
              
                      @Override
                      public void onStartup(ServletContext servletContext)
                              throws ServletException {
                          WebApplicationContext context = getContext();
                          servletContext.addListener(new ContextLoaderListener(context));
                          ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
                          dispatcher.setLoadOnStartup(1);
                          dispatcher.addMapping("/*");
                      }
              
                      private AnnotationConfigWebApplicationContext getContext() {
                          AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
                          context.register(com.raghu.dashboard.config.WebConfig.class);
                          context.scan("com.raghu.dashboard.api");
                          return context;
                      }
              
                  }
              

              还要确保返回的 Object 具有正确的 getter 和 setter。

              例子:

              @RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
              @ResponseBody
              public ResponseEntity<TaskInfo> findAll() {
                  logger.info("Calling the findAll1()");
                  TaskInfo taskInfo = dashboardService.getTasks();
                  HttpHeaders headers = new HttpHeaders();
                  headers.add("Access-Control-Allow-Origin", "*");
                  ResponseEntity<TaskInfo> entity = new ResponseEntity<TaskInfo>(taskInfo,
                          headers, HttpStatus.OK);
                  logger.info("entity is := " + entity);
                  return entity;
              }
              

              TaskInfo 对象应该有适当的 getter 和 setter。否则会抛出 406 错误。

              POM 文件供参考:

              <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
                  <modelVersion>4.0.0</modelVersion>
                  <groupId>com.raghu.DashBoardService</groupId>
                  <artifactId>DashBoardService</artifactId>
                  <packaging>war</packaging>
                  <version>0.0.1-SNAPSHOT</version>
                  <name>DashBoardService Maven Webapp</name>
                  <url>http://maven.apache.org</url>
                  <properties>
                      <!-- Spring -->
                      <spring-framework.version>4.0.6.RELEASE</spring-framework.version>
                      <jackson.version>2.4.0</jackson.version>
                      <jaxb-api.version>2.2.11</jaxb-api.version>
                      <log4j.version>1.2.17</log4j.version>
                  </properties>
              
                  <dependencies>
                      <dependency>
                          <groupId>junit</groupId>
                          <artifactId>junit</artifactId>
                          <version>3.8.1</version>
                          <scope>test</scope>
                      </dependency>
              
                      <dependency>
                          <groupId>org.mongodb</groupId>
                          <artifactId>mongo-java-driver</artifactId>
                          <version>2.10.1</version>
                      </dependency>
                      <!-- Spring Data Mongo Support -->
                      <dependency>
                          <groupId>org.springframework.data</groupId>
                          <artifactId>spring-data-mongodb</artifactId>
                          <version>1.4.1.RELEASE</version>
                      </dependency>
              
                      <dependency>
                          <groupId>org.springframework</groupId>
                          <artifactId>spring-beans</artifactId>
                          <version>${spring-framework.version}</version>
                      </dependency>
              
                      <dependency>
                          <groupId>org.springframework</groupId>
                          <artifactId>spring-core</artifactId>
                          <version>${spring-framework.version}</version>
                      </dependency>
              
                      <dependency>
                          <groupId>org.springframework</groupId>
                          <artifactId>spring-context</artifactId>
                          <version>${spring-framework.version}</version>
                      </dependency>
              
                      <dependency>
                          <groupId>org.springframework</groupId>
                          <artifactId>spring-web</artifactId>
                          <version>${spring-framework.version}</version>
                      </dependency>
              
                      <dependency>
                          <groupId>org.springframework</groupId>
                          <artifactId>spring-webmvc</artifactId>
                          <version>${spring-framework.version}</version>
                      </dependency>
                      <dependency>
                          <groupId>cglib</groupId>
                          <artifactId>cglib</artifactId>
                          <version>3.1</version>
                      </dependency>
              
                      <dependency>
                          <groupId>org.springframework</groupId>
                          <artifactId>spring-expression</artifactId>
                          <version>${spring-framework.version}</version>
                      </dependency>
              
                      <dependency>
                          <groupId>org.springframework</groupId>
                          <artifactId>spring-aop</artifactId>
                          <version>${spring-framework.version}</version>
                      </dependency>
              
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-tx</artifactId>
                  <version>${spring-framework.version}</version>
              </dependency>
              
              
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-dao</artifactId>
                  <version>2.0.3</version>
              </dependency>
              
              
              
                      <!-- Jackson mapper -->
                      <dependency>
                          <groupId>com.fasterxml.jackson.core</groupId>
                          <artifactId>jackson-core</artifactId>
                          <version>2.2.3</version>
                      </dependency>
                      <dependency>
                          <groupId>com.fasterxml.jackson.core</groupId>
                          <artifactId>jackson-databind</artifactId>
                          <version>2.2.3</version>
                      </dependency>
                      <dependency>
                          <groupId>com.fasterxml.jackson.core</groupId>
                          <artifactId>jackson-annotations</artifactId>
                          <version>2.2.3</version>
                      </dependency>
              
                      <dependency>
                          <groupId>javax.servlet</groupId>
                          <artifactId>javax.servlet-api</artifactId>
                          <version>3.0.1</version>
                      </dependency>
              
                      <dependency>
                          <groupId>com.google.code.gson</groupId>
                          <artifactId>gson</artifactId>
                          <version>1.7.1</version>
                      </dependency>
              
                      <!-- Log4j -->
                      <dependency>
                          <groupId>log4j</groupId>
                          <artifactId>log4j</artifactId>
                          <version>${log4j.version}</version>
                      </dependency>
              
                      <dependency>
                          <groupId>org.springframework.data</groupId>
                          <artifactId>spring-data-commons</artifactId>
                          <version>1.5.0.RELEASE</version>
                      </dependency>
              
                  </dependencies>
              
                  <build>
                      <finalName>DashBoardService</finalName>
                      <resources>
                          <resource>
                              <directory>src/main/resources</directory>
                              <filtering>true</filtering>
                          </resource>
                      </resources>
                      <plugins>
                          <plugin>
                              <groupId>org.apache.maven.plugins</groupId>
                              <artifactId>maven-compiler-plugin</artifactId>
                              <version>3.5.1</version>
                              <configuration>
                                  <source>1.8</source>
                                  <target>1.8</target>
                              </configuration>
                          </plugin>
                          <plugin>
                              <groupId>org.apache.maven.plugins</groupId>
                              <artifactId>maven-war-plugin</artifactId>
                              <version>2.6</version>
                              <configuration>
                                  <failOnMissingWebXml>false</failOnMissingWebXml>
                              </configuration>
                          </plugin>
                      </plugins>
                  </build>
              
              </project>
              

              【讨论】:

              • 对我来说这也解决了问题,但我不知道为什么?有什么解释吗?
              【解决方案14】:

              嗯,这个页面上的答案可能是正确的,但他们没有很好地阐述。这就是我所做的

              我将此添加到我的 pom.xml 中

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

              然后我将标题添加到我的 RequestMapping 中,如下所示

              @RequestMapping(value="/admin/getGallery", method = RequestMethod.GET, headers={"Content-Type=application/json"})
              

              然后在我的 jquery ajax 中添加了 - contentType: "application/json",所以看起来像

              jQuery.ajax({
                          type:'GET',
                          url:"getGallery.html",
                          data: "designId="+designId,
                          processData:false,
                          contentType: "application/json",
                          //dataType: "json",
                         success:function(data){
                            console.log(data);
              
                         },
                          error : function(e) {
                              console.log("ERROR: ", e);
                          },
                      });
              

              然后在我的servlet中我添加了

              <bean id="jsonHttpMessageConverter"
                  class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
                  <!-- Bind the return value of the Rest service to the ResponseBody. -->
                  <bean
                  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
                  <property name="messageConverters">
                  <util:list id="beanList">
                  <ref bean="jsonHttpMessageConverter" />
                  </util:list>
                  </property>
              </bean> 
              

              如果您的 servlet 中的 util 标签有问题,只需添加同一个 servlet 文件即可

              xmlns:util="http://www.springframework.org/schema/util"
              

              xsi:schemaLocation="http://www.springframework.org/schema/util
              http://www.springframework.org/schema/util/spring-util-3.0.xsd
              

              【讨论】:

              • 如果 Spring 版本 >4,那么您必须将 class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter 更改为 class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter。根据andreagirardi.it/blog/…
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2020-11-21
              • 2013-02-19
              • 2018-01-23
              • 1970-01-01
              • 2014-04-11
              • 2011-11-12
              • 1970-01-01
              相关资源
              最近更新 更多