Spring 3 + JSON的问题:HTTP状态406?

我试图通过在SpringMVC 3.0项目中通过Ajax发送状态名来获取城市列表。 为此,我在JSP中使用了以下调用(使用jQuery):

 function getCities() { jq(function() { jq.post("getCities.html", { stateSelect: jq("#stateSelect").val()}, function(data){ jq("#cities").replaceWith('Testing'); }); }); }  

这是我的控制器代码:

 @RequestMapping(value = "/getCities", method = RequestMethod.POST) public @ResponseBody List getCities(@RequestParam(value="stateSelect", required=true) String stateName, Model model) { // Delegate to service to do the actual adding List 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 Not Acceptable请求的资源只能根据请求中发送的Accept标头生成不可接受的内容。

我在我的Maven依赖项中使用过Jackson并在我的上下文文件中定义了。 我已经广泛搜索了,我猜问题是@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 

请指导我。 我究竟做错了什么?? 救命!!

正如彼得在评论中写道的那样,问题的原因是Spring无法加载jackson。 默认情况下,它不会被依赖项加载。 在我添加了依赖项之后

   org.codehaus.jackson jackson-jaxrs 1.9.2  

在浏览器中输入地址后返回了JSON,没有任何带有Accept标头的技巧(正如它应该做的那样)。

在Tomcat 7.0上测试过。

你有错误的响应内容类型它应该是application / json。

您需要将jackson添加到/ lib目录中。

你应该有

  

在您的serlvet-name.xml文件中。

另外,我建议您将请求映射为get并尝试使用Google Chrome进行浏览,以查看其是否返回正确的结果。 它具有非常好的json表示。

问题不在服务器端,而是在客户端上。

仔细查看错误消息:请求的资源( 由服务器端生成 )只能根据请求中发送的Accept头生成不可接受的内容( JSON )( 由客户端! )。

检查您的请求标头:

接受* / *

试试这种方式:

 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('Testing'); }, "json" // Data type you are expecting from server ); }); } 

这会将您的Accept标头更改为以下内容(从jQuery 1.5开始):

接受:application / json,text / javascript,* / *;  Q = 0.01

这将明确告诉服务器端您期望JSON。

使用jQuery,您可以将contentType设置为所需的内容(application / json; charset = UTF-8’),并在服务器端设置相同的标头。

记得在测试时清除高速缓存。

在使用Apache HTTPClient调用少量服务时,我也遇到了类似的问题。 问题是客户端而不是服务器。 我使用了HTTPRequester,头部接受了application / json,它运行正常。