spring mvc不返回json内容——错误406

时间:2021-01-12 18:03:18

I am using Spring MVC with JSON as specified in Ajax Simplification Spring 3.0 article.

我正在使用Spring MVC和JSON,如Ajax简单化Spring 3.0文章中所述。

After so many attempts and variations of my code depending on advice found on various forums, my code still doesn't work.

在我的代码依赖于各种论坛上的建议之后,我的代码有那么多的尝试和变化,但是我的代码仍然不能工作。

I keep on getting the following error: (406) The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().

我一直得到以下错误:(406)此请求标识的资源只能生成根据请求“accept”标头()不能接受的特征的响应。

I have in my appconfig.xml as required.

在appconfig中。xml作为必需的。

app-config.xml

app-config.xml

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

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

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>

This is what I have for my controller

这是我的控制器。

@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 call

jsp jquery调用

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

I would really appreciate any input on this issue. Thank you

我非常感谢在这个问题上的任何意见。谢谢你!

13 个解决方案

#1


8  

Try remove the header limitation for Accept, put a breakpoint and see what's the actual value. Or do this with FireBug.

尝试删除Accept的头部限制,放置一个断点并查看实际值。或者用FireBug。

Also take a look at this jquery issue

另外,看看这个jquery问题。

#2


23  

To return JSON response from @ResponseBody-annotated method, you need two things:

要从@ responsebody注释的方法返回JSON响应,需要以下两点:

  • <mvc:annotation-driven /> (you already have it)
  • (已经有了)
  • Jackson JSON Mapper in the classpath
  • 类路径中的Jackson JSON映射器

You don't need ContentNegotiatingViewResolver and headers in @RequestMapping.

您不需要在@RequestMapping中使用content谈判者viewresolver和header。

#3


18  

I had this problem after I upgraded Spring to 4.1.x from 3.2.x. I fixed by upgrading Jackson from 1.9.x to 2.2.x (fasterxml)

在我将Spring升级到4.1之后,我遇到了这个问题。从3.2.x x。我把杰克逊从1.9升级到1.9。2.2 x。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>

#4


8  

Add org.springframework.http.converter.json.MappingJacksonHttpMessageConverter and org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter to DispatcherServlet-servlet.xml. and refer to the the first one in the second using

添加org.springframework.http.converter.json。MappingJacksonHttpMessageConverter org.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>

#5


3  

I too got this error and while debugging deep down into the rabbit hole i came across this exception

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

java.lang.IllegalArgumentException: Conflicting getter definitions for property "error": com.mycomp.model.OutputJsonModel#isError(0 params) vs com.mycomp.model.OutputJsonModel#getError(0 params)

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

So basically in my java bean i had something like the following:

在我的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;
}

Changing one of the error member variable name to something else solved the issues.

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

#6


2  

I had this problem too, you have to add <mvc:annotation-driven /> in your configuration xml

我也有这个问题,您必须在配置xml中添加

and

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

in your pom.xml

在你pom.xml

#7


2  

I have used java configuration and i got this same error. I have missed to add the @EnableWebMvc to the configuration file. This error is resolved after i add the @EnableWebMvc in my webconfig file.

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

Also the Object that is returned from your Spring Controller, should have proper getter and setter methods.

同样,从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

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;
        }

    }

Also make sure the Object that is returned, has the proper getter and setter.

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

Example:

例子:

@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 object should have proper getter and setter. if not, 406 error will be thrown.

TaskInfo对象应该有合适的getter和setter。如果没有,将抛出406错误。

POM File for Reference:

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>

#8


1  

issue is not related to jquery . even bug is saying it is server side issue . please make sure that following 2 jar present in class path :-

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

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

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

#9


1  

I also faced this same issue and I downloaded this [jar]: (http://www.java2s.com/Code/Jar/j/Downloadjacksonall190jar.htm)! and placed in lib folder and the app works like a charm :)

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

#10


1  

See my answer to a similar problem here with Spring MVC interpreting the extension of the URI and changing the expected MIME type produced behind the scene, therefore producing a 406.

请参见我对类似问题的回答:Spring MVC解释了URI的扩展,并更改了幕后生成的预期MIME类型,从而生成了406。

#11


0  

As said by axtavt, mvc:annotation-driven and jackson JSON mapper are all that you need. I followed that and got my application to return both JSON and XML strings from the same method without changing any code, provided that there are @XmlRootElement and @XmlElement in the object you are returning from the controller. The difference was in the accept parameter passed in the request or header. To return xml, any normal invocation from the browser will do it, otherwise pass the accept as 'application/xml'. If you want JSON returned, use 'application/json' in the accept parameter in request.

正如axtavt所说,您只需要mvc:注解驱动和jackson JSON映射器。我遵循了这一点,并让我的应用程序在不改变任何代码的情况下,从相同的方法返回JSON和XML字符串,前提是在从控制器返回的对象中有@XmlRootElement和@XmlElement。不同之处在于在请求或报头中传递的accept参数。要返回xml,浏览器中的任何正常调用都将这样做,否则将接受作为“application/xml”传递。如果希望返回JSON,请在request中的accept参数中使用“application/ JSON”。

If you use firefox, you can use tamperdata and change this parameter

如果您使用firefox,您可以使用tamperdata并更改此参数

#12


0  

Using jQuery , you can set contentType to desired one (application/json; charset=UTF-8' here) and set same header at server side.

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

REMEMBER TO CLEAR CACHE WHILE TESTING.

记得在测试时清除缓存。

#13


0  

Instead of @RequestMapping(...headers="Accept=application/json"...) use @RequestMapping(... , produces = "application/json")

而不是@RequestMapping(…header ="Accept=application/json"…)使用@RequestMapping(…application / json,产生= " ")

#1


8  

Try remove the header limitation for Accept, put a breakpoint and see what's the actual value. Or do this with FireBug.

尝试删除Accept的头部限制,放置一个断点并查看实际值。或者用FireBug。

Also take a look at this jquery issue

另外,看看这个jquery问题。

#2


23  

To return JSON response from @ResponseBody-annotated method, you need two things:

要从@ responsebody注释的方法返回JSON响应,需要以下两点:

  • <mvc:annotation-driven /> (you already have it)
  • (已经有了)
  • Jackson JSON Mapper in the classpath
  • 类路径中的Jackson JSON映射器

You don't need ContentNegotiatingViewResolver and headers in @RequestMapping.

您不需要在@RequestMapping中使用content谈判者viewresolver和header。

#3


18  

I had this problem after I upgraded Spring to 4.1.x from 3.2.x. I fixed by upgrading Jackson from 1.9.x to 2.2.x (fasterxml)

在我将Spring升级到4.1之后,我遇到了这个问题。从3.2.x x。我把杰克逊从1.9升级到1.9。2.2 x。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>

#4


8  

Add org.springframework.http.converter.json.MappingJacksonHttpMessageConverter and org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter to DispatcherServlet-servlet.xml. and refer to the the first one in the second using

添加org.springframework.http.converter.json。MappingJacksonHttpMessageConverter org.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>

#5


3  

I too got this error and while debugging deep down into the rabbit hole i came across this exception

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

java.lang.IllegalArgumentException: Conflicting getter definitions for property "error": com.mycomp.model.OutputJsonModel#isError(0 params) vs com.mycomp.model.OutputJsonModel#getError(0 params)

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

So basically in my java bean i had something like the following:

在我的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;
}

Changing one of the error member variable name to something else solved the issues.

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

#6


2  

I had this problem too, you have to add <mvc:annotation-driven /> in your configuration xml

我也有这个问题,您必须在配置xml中添加

and

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

in your pom.xml

在你pom.xml

#7


2  

I have used java configuration and i got this same error. I have missed to add the @EnableWebMvc to the configuration file. This error is resolved after i add the @EnableWebMvc in my webconfig file.

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

Also the Object that is returned from your Spring Controller, should have proper getter and setter methods.

同样,从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

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;
        }

    }

Also make sure the Object that is returned, has the proper getter and setter.

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

Example:

例子:

@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 object should have proper getter and setter. if not, 406 error will be thrown.

TaskInfo对象应该有合适的getter和setter。如果没有,将抛出406错误。

POM File for Reference:

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>

#8


1  

issue is not related to jquery . even bug is saying it is server side issue . please make sure that following 2 jar present in class path :-

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

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

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

#9


1  

I also faced this same issue and I downloaded this [jar]: (http://www.java2s.com/Code/Jar/j/Downloadjacksonall190jar.htm)! and placed in lib folder and the app works like a charm :)

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

#10


1  

See my answer to a similar problem here with Spring MVC interpreting the extension of the URI and changing the expected MIME type produced behind the scene, therefore producing a 406.

请参见我对类似问题的回答:Spring MVC解释了URI的扩展,并更改了幕后生成的预期MIME类型,从而生成了406。

#11


0  

As said by axtavt, mvc:annotation-driven and jackson JSON mapper are all that you need. I followed that and got my application to return both JSON and XML strings from the same method without changing any code, provided that there are @XmlRootElement and @XmlElement in the object you are returning from the controller. The difference was in the accept parameter passed in the request or header. To return xml, any normal invocation from the browser will do it, otherwise pass the accept as 'application/xml'. If you want JSON returned, use 'application/json' in the accept parameter in request.

正如axtavt所说,您只需要mvc:注解驱动和jackson JSON映射器。我遵循了这一点,并让我的应用程序在不改变任何代码的情况下,从相同的方法返回JSON和XML字符串,前提是在从控制器返回的对象中有@XmlRootElement和@XmlElement。不同之处在于在请求或报头中传递的accept参数。要返回xml,浏览器中的任何正常调用都将这样做,否则将接受作为“application/xml”传递。如果希望返回JSON,请在request中的accept参数中使用“application/ JSON”。

If you use firefox, you can use tamperdata and change this parameter

如果您使用firefox,您可以使用tamperdata并更改此参数

#12


0  

Using jQuery , you can set contentType to desired one (application/json; charset=UTF-8' here) and set same header at server side.

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

REMEMBER TO CLEAR CACHE WHILE TESTING.

记得在测试时清除缓存。

#13


0  

Instead of @RequestMapping(...headers="Accept=application/json"...) use @RequestMapping(... , produces = "application/json")

而不是@RequestMapping(…header ="Accept=application/json"…)使用@RequestMapping(…application / json,产生= " ")