springMVC不返回JSON的内容 – 错误406
我正在使用Ajax Simplification Spring 3.0文章中指定的JSON使用Spring MVC。
经过这么多的尝试和我的代码的变化取决于在各种论坛上发现的build议,我的代码仍然无法正常工作。
我继续得到以下错误:(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); }); }
我真的很感谢在这个问题上的任何投入。 谢谢
尝试删除Accept
的头部限制,放一个断点,看看实际的值是多less。 或者用FireBug做这个。
另外看看这个jQuery的问题
要从@ResponseBody
-annotated方法返回JSON响应,您需要两件事情:
-
<mvc:annotation-driven />
(你已经拥有了) - jacksonJSON映射器在classpath中
您不需要ContentNegotiatingViewResolver
和@RequestMapping
headers
。
在从3.2.x升级到4.1.x之后,我遇到了这个问题。 我修正了从1.9.x升级到2.2.x(更快的xml)
<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>
将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>
我也得到这个错误,同时debugging深入兔子洞,我遇到了这个例外
java.lang.IllegalArgumentException:属性“error”的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; }
将其中一个错误成员variables名更改为别的东西来解决问题。
我也有这个问题,你必须在你的configurationXML中添加<mvc:annotation-driven />
和
<!-- Jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.databind-version}</version> </dependency>
在你的pom.xml中
我已经使用Javaconfiguration,我得到了这个相同的错误。 我错过了将@EnableWebMvc添加到configuration文件。 在我的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; } }
还要确保返回的对象具有适当的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>
问题与jquery无关。 甚至错误是说这是服务器端问题。 请确保在课程path中存在以下2个jar: –
jackson-core-asl-1.9.X.jar jackson-mapper-asl-1.9.X.jar
我也遇到了同样的问题,我下载了这个[jar]:( http://www.java2s.com/Code/Jar/j/Downloadjacksonall190jar.htm )! 并放置在lib文件夹和应用程序就像一个魅力:)
Spring MVC解释了URI的扩展,并改变了场景后面产生的期望的MIMEtypes,因此产生了一个406。
正如axtavt所说,mvc:注释驱动和jacksonJSON映射器都是你需要的。 我跟着它,让我的应用程序返回来自同一个方法的JSON和XMLstring,而不改变任何代码,只要在从控制器返回的对象中有@XmlRootElement和@XmlElement。 差异在于在请求或头中传递的accept参数。 要返回XML,从浏览器的任何正常调用将做到这一点,否则传递接受为'应用程序/ XML'。 如果您想要返回JSON,请在请求中的accept参数中使用“application / json”。
如果你使用firefox,你可以使用tamperdata并改变这个参数
使用jQuery,您可以将contentType设置为所需的(application / json; charset = UTF-8),并在服务器端设置相同的头文件。
记住testing时清除高速caching。
而不是@RequestMapping(...headers="Accept=application/json"...)
使用@RequestMapping(... , produces = "application/json")