2010-11-01 62 views
26

我使用的是与在Ajax Simplification Spring 3.0 article中指定的JSON的Spring MVC。春天mvc不返回json的内容 - 错误406

经过这么多的尝试和我的代码的变化取决于在各种论坛上发现的建议,我的代码仍然无法正常工作。

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

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

我真的很感谢在这个问题上的任何意见。 谢谢

回答

8

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

this jquery issue

+3

太谢谢你了。根据文章,accept头应该被设置为*/*。所以我更新了请求映射到:@RequestMapping(value =“/ working”,headers =“Accept = */*”,method = RequestMethod.GET)现在它工作:)) – serena 2010-11-01 20:12:15

23

@ResponseBody -annotated方法返回JSON响应,你需要两样东西:

你不在@RequestMapping中不需要ContentNegotiatingViewResolverheaders

+0

我已删除了ContentNegotiatingViewResolver和标头信息,但它仍然没有工作。当你在类路径中说,这是否意味着我必须导入杰克逊的库?如果是的话,我把它们包括在内 – serena 2010-11-01 20:02:12

+0

然后threre在你的问题上不明确的事情:app-config.xml与DispatcherServlet的'...- servlet.xml'配置有什么关系? – axtavt 2010-11-01 20:16:21

+0

在web.xml中,我指定了servlet,然后app-config.xml(contextConfigLocation): 调度程序 org.springframework.web.servlet.DispatcherServlet ​​contextConfigLocation的 /WEB-INF/app-config.xml <负载上启动> 1 serena 2010-11-01 20:26:02

0

而且看一看正如axtavt,MVC说:注释驱动和杰克逊JSON映射器是所有你所需要的。我跟着它,让我的应用程序从同一个方法返回JSON和XML字符串,而不更改任何代码,前提是从控制器返回的对象中有@XmlRootElement和@XmlElement。差异在于请求或头中传递的accept参数。要返回xml,任何来自浏览器的正常调用都会执行,否则将accept作为“application/xml”传递。如果您想要返回JSON,请在请求中的accept参数中使用'application/json'。

如果你使用Firefox,你可以使用tamperdata和更改这个参数

3

我也得到了这个错误,而调试深处进了兔子洞我遇到了这个例外

java.lang.IllegalArgumentException: Conflicting getter definitions for property "error": 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; 
} 

将其中一个错误成员变量名更改为别的东西来解决问题。

+0

谢谢你的回答,让我意识到我忘记了getter和setter方法。 – Dinei 2015-10-14 02:48:21

+0

我有同样的问题。确保响应对象具有getter和setter。 – user1885834 2016-11-15 11:50:37

1

问题与jquery无关。甚至错误是说它是服务器端问题。请确保以下两个罐子出现在类路径: -

杰克逊核心ASL-1.9.X.jar 杰克逊映射器-ASL-1.9.X.jar

+0

当我从1.9.x jackson切换到2.x(fasterxml)时,这个版本修复了这个问题。我只导入了核心,但没有注释或数据绑定。 我不满意删除接受选项。 – Chanoch 2014-05-02 15:32:40

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> 
+0

非常感谢,这对我有用!只有改变是重命名MappingJacksonHttpMessageConverter到你的片段中的MappingJackson2HttpMessageConverter,这是最新的春季版本 - 4.2.0.RELEASE – vanval 2016-02-11 22:56:03

0

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

0

使用jQuery,可以设置的contentType到期望的一个(应用/ JSON;字符集= UTF-8' 在这里)并在服务器端设置相同的标题。

请记住清除高速缓存,然后进行测试。

2

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

<!-- Jackson --> 
     <dependency> 
      <groupId>com.fasterxml.jackson.core</groupId> 
      <artifactId>jackson-databind</artifactId> 
      <version>${jackson.databind-version}</version> 
     </dependency> 
在你的pom.xml

18

我从3.2.x升级到4.1.x后出现了这个问题。我固定通过从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> 
+0

Thx伙计,问题让我疯狂! – 2015-07-21 08:05:39

+0

这是我的问题的答案。谢啦。 – 2016-04-21 19:09:05

2

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

另外,从Spring Controller返回的对象应该有适当的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; 
     } 

    } 

还要确保返回的对象,有适当的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对象应该有适当的获取和设置。如果不是,将会抛出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> 
+0

对我来说,这也解决了这个问题,但我不知道为什么?任何解释? – Shady 2017-07-13 21:45:33

相关问题