【发布时间】:2014-02-09 17:01:55
【问题描述】:
我想从我的控制器发送 JSON。我有以下配置。
spring-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<context:component-scan base-package="com.castle.controllers"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
.js:
function testAjax() {
var data = {userName: "MyUsername", password:"Password"};
$.ajax({
url: 'ajax/test.htm',
dataType : 'json',
type : 'POST',
contentType: "application/json",
data: JSON.stringify(data),
success: function(response){
alert('Load was performed.');
}
});
}
UserTest.java:
public class UserTest {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
TestAjaxController.java :
@Controller
@RequestMapping("/ajax")
public class TestAjaxController {
@RequestMapping(method = RequestMethod.POST, value = "/test.htm")
public @ResponseBody
UserTest testAjaxRequest(@RequestBody UserTest user) {
return user;
}
}
pom.xml:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
当我做这个请求时,我得到了表示为 UserTest 对象的控制器 JSON。但返回时:
HTTP 状态 406 - 此请求标识的资源只能生成具有根据请求“接受”标头不可接受的特征的响应。
我做错了什么?我知道,有很多关于这种情况的问题,但我不能解决它 2 天...
更新
我找到了解决方案!!
它只需要返回一个对象。不是用户对象或其他东西。
但
return Object;
public @ResponseBody Object testAjaxRequest(@RequestBody UserTest user) {
List<UserTest> list = new ArrayList<>();
list.add(user);
list.add(user);
list.add(user);
return list;
【问题讨论】:
-
需要返回对象。在这种情况下,您无需在配置文件中指定任何内容。
标签: java jquery json spring spring-mvc