2010-11-01 68 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