26

我正在使用带有 JSON 的 Spring MVC,如Ajax Simplification Spring 3.0 文章中所述

根据在各种论坛上找到的建议对我的代码进行了如此多的尝试和变体之后,我的代码仍然无法正常工作。

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

根据需要,我在我的 appconfig.xml 中有。

应用程序配置.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);
    });
  }

我非常感谢您对此问题的任何意见。谢谢

4

14 回答 14

23

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

你不需要ContentNegotiatingViewResolverheadersin @RequestMapping

于 2010-11-01T14:51:18.423 回答
18

在我将 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>
于 2015-01-04T16:40:51.417 回答
9

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

也看看这个 jquery 问题

于 2010-11-01T14:51:31.383 回答
8

添加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>
于 2013-09-26T12:05:23.757 回答
3

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

java.lang.IllegalArgumentException:属性“错误”的吸气剂定义冲突: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;
}

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

于 2012-09-27T15:46:14.440 回答
2

我也有这个问题,你必须添加<mvc:annotation-driven />你的配置xml

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

在你的 pom.xml

于 2014-10-22T14:41:48.350 回答
2

我使用了 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>
于 2016-03-07T09:18:30.757 回答
1

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

于 2014-08-09T14:28:22.087 回答
1

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

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

于 2013-06-01T12:16:04.637 回答
1

在这里查看我对类似问题的回答,Spring MVC 解释 URI 的扩展并更改在幕后产生的预期 MIME 类型,因此产生 406。

于 2015-05-11T12:45:04.090 回答
1

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

我将此添加到我的 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
于 2018-08-12T14:14:14.677 回答
0

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

记住在测试时清除缓存。

于 2014-02-06T20:51:07.853 回答
0

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

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

于 2011-08-31T19:12:56.723 回答
0

而不是@RequestMapping(...headers="Accept=application/json"...)使用@RequestMapping(... , produces = "application/json")

于 2013-12-07T09:11:55.593 回答