我正在使用Ajax Simplification Spring 3.0 article中指定的带有JSON的Spring MVC。
根据各种论坛上的建议,经过我的代码的大量尝试和变化后,我的代码仍无效。
我继续收到以下错误:(406)此请求标识的资源只能根据请求“accept”标题()生成具有不可接受特征的响应。
我根据需要在appconfig.xml中。
应用-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 call
function convertToDecimal(){
$.getJSON("convert/working", {key: "r"}, function(aConversion){
alert("it worked.");
$('#decimal').val(aConversion.input);
});
}
我真的很感激有关此问题的任何意见。 谢谢
答案 0 :(得分:23)
要从@ResponseBody
- 带注释的方法返回JSON响应,您需要做两件事:
<mvc:annotation-driven />
(你已经拥有它) ContentNegotiatingViewResolver
中您不需要headers
和@RequestMapping
。
答案 1 :(得分:18)
我从3.2.x将Spring升级到4.1.x后遇到了这个问题。我通过将Jackson从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>
答案 2 :(得分:8)
尝试删除Accept
的标题限制,设置断点并查看实际值。或者使用FireBug执行此操作。
答案 3 :(得分:8)
将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>
答案 4 :(得分:3)
我也遇到了这个错误,当我深入调试兔子洞时,我遇到了这个异常
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;
}
将错误成员变量名之一更改为其他内容解决了问题。
答案 5 :(得分: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中的
答案 6 :(得分:2)
我使用过java配置,我也遇到了同样的错误。我错过了将@EnableWebMvc添加到配置文件中。在我的webconfig文件中添加@EnableWebMvc后,此错误得以解决。
从Spring Controller返回的Object也应该有适当的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>
答案 7 :(得分:1)
问题与jquery无关。甚至bug都说它是服务器端问题。请确保在课程路径中出现以下2个jar: -
杰克逊核-ASL-1.9.X.jar 杰克逊映射器-ASL-1.9.X.jar
答案 8 :(得分:1)
我也遇到了同样的问题,我下载了这个[jar] :( http://www.java2s.com/Code/Jar/j/Downloadjacksonall190jar.htm)!并放在lib文件夹中,该应用程序就像一个魅力:)
答案 9 :(得分:1)
使用Spring MVC查看my answer to a similar problem here解释URI的扩展并更改场景后面生成的预期MIME类型,从而生成406。
答案 10 :(得分: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
答案 11 :(得分:0)
正如axtavt所说,mvc:annotation-driven和jackson JSON mapper就是你所需要的。我遵循了这一点,让我的应用程序在不更改任何代码的情况下从同一方法返回JSON和XML字符串,只要在从控制器返回的对象中有@XmlRootElement和@XmlElement。区别在于请求或标头中传递的accept参数。要返回xml,浏览器的任何正常调用都会执行,否则将accept作为'application / xml'传递。如果要返回JSON,请在请求中的accept参数中使用'application / json'。
如果您使用firefox,则可以使用tamperdata并更改此参数
答案 12 :(得分:0)
而不是@RequestMapping(...headers="Accept=application/json"...)
使用@RequestMapping(... , produces = "application/json")
答案 13 :(得分:0)
使用jQuery,您可以将contentType设置为所需的内容(application / json; charset = UTF-8'),并在服务器端设置相同的标头。
记住在测试时清除高速缓存。