我正在尝试通过在SpringMVC 3.0项目中通过Ajax发送状态名来获取城市列表。 为此,我在JSP中使用了以下调用(使用jQuery):
<script type="text/javascript">
function getCities() {
jq(function() {
jq.post("getCities.html",
{ stateSelect: jq("#stateSelect").val()},
function(data){
jq("#cities").replaceWith('<span id="cities">Testing</span>');
});
});
}
</script>
这是我的控制器代码:
@RequestMapping(value = "/getCities", method = RequestMethod.POST)
public @ResponseBody List<StateNames> getCities(@RequestParam(value="stateSelect", required=true) String stateName,
Model model) {
// Delegate to service to do the actual adding
List<StateNames> listStates = myService.listCityNames(stateName);
// @ResponseBody will automatically convert the returned value into JSON format
// You must have Jackson in your classpath
return listStates;
}
但是当我运行它时,我收到HTTP 406错误说明以下内容: 406不可接受 请求的资源只能根据请求中发送的Accept标头生成不可接受的内容。
我在我的Maven依赖项中使用过Jackson。已在我的上下文文件中定义。 我广泛搜索过&amp;我想问题是@ResponseBody不会自动将我的List转换为适当的JSON对象。
我的萤火虫说:
Response Headers
Server Apache-Coyote/1.1
Content-Type text/html;charset=utf-8
Content-Length 1070
Date Sat, 12 Feb 2011 13:09:44 GMT
Request Headers
Host localhost:8080
User-Agent Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13
Accept */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Content-Type application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With XMLHttpRequest
Referer http://localhost:8080/MyApplication/
Content-Length 17
Cookie JSESSIONID=640868A479C40792F8AB3DE118AF12E0
Pragma no-cache
Cache-Control no-cache
请指导我。我究竟做错了什么?? HELP !!
答案 0 :(得分:8)
正如彼得在评论中写道的那样,问题的原因是Spring无法加载杰克逊。默认情况下,它不会被依赖项加载。在我添加了依赖项
之后 <dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.2</version>
</dependency>
在浏览器中输入地址后返回了JSON,没有任何带有Accept标头的技巧(正如它应该做的那样)。
在Tomcat 7.0上测试。
答案 1 :(得分:7)
你有错误的响应内容类型它应该是application / json。
您需要将jackson添加到/ lib目录中。
你应该
<mvc:annotation-driven />
在您的serlvet-name.xml文件中。
此外,我建议您将您的请求映射为get并尝试使用Google Chrome浏览,以查看它是否返回正确的结果。它具有非常好的json表示。
答案 2 :(得分:3)
问题不在服务器端,而是在客户端上。
仔细查看错误消息:请求的资源(由服务器端生成)仅能够生成不可接受的内容( JSON )(由客户端!)根据请求中发送的Accept标头。
检查您的请求标题:
Accept */*
尝试这种方式:
function getCities() {
jq(function() {
jq.post(
"getCities.html", // URL to post to
{ stateSelect: jq("#stateSelect").val() }, // Your data
function(data) { // Success callback
jq("#cities").replaceWith('<span id="cities">Testing</span>');
},
"json" // Data type you are expecting from server
);
});
}
这会将Accept标头更改为以下内容(从jQuery 1.5开始):
Accept: application/json, text/javascript, */*; q=0.01
这将显式告诉服务器端您期望JSON。
答案 3 :(得分:0)
使用jQuery,您可以将contentType设置为所需的内容(application / json; charset = UTF-8'),并在服务器端设置相同的标头。
记住在测试时清除高速缓存。
答案 4 :(得分:-1)
在使用Apache HTTPClient调用少量服务时,我也遇到了类似的问题。问题是客户端而不是服务器。我使用了HTTPRequester,头部接受了application / json,它工作正常。