Spring Jquery Ajax Post上的400错误请求

时间:2012-10-25 18:40:37

标签: jquery spring-mvc http-post

我在此POST请求中收到400错误请求。知道这里的问题是什么吗?日志为here

控制器

@Controller
public class AjaxController {
    @RequestMapping(value="/addKeys", method=RequestMethod.POST, consumes="application/json; charset=UTF-8")
    public ResponseEntity<String> addKeys(@RequestParam(value="keys") ArrayList<Keys> keys){
        System.out.println("::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"+keys);
    }
}

上下文servlet.xml中

<beans>
    <mvc:annotation-driven />
    <context:component-scan base-package="com.canon.fw.controller" />
    <bean id="defaultViews" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</beans>

的Ajax

tmpList = '[{"key":"camera","label":"Camera"},{"key":"mobile","label":"Mobile"}]';
$.ajax({
  type: 'POST',
  url: ctx+'/ajx/addKeys',
  data: JSON.stringify({"keys": tmpList }),
  success: function(r){
      if(r.model.status=='success'){
          debugger;
          //glist.push(elem.key);
          //addToList(elem.key, elem.label);
          highlightInfoDisc();
      }
  },
  dataType: 'json',
  contentType: 'application/json'
});

FireBug - 网址

http://localhost:8080/Di/ajx/addKeys

Firebug - 响应标头

Cache-Control   must-revalidate,no-cache,no-store
Content-Length  1384
Content-Type    text/html; charset=iso-8859-1
Server  Jetty(6.1.26)

Firebug - 请求标题

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Connection  keep-alive
Content-Length  74
Content-Type    application/json; charset=UTF-8
Cookie  JSESSIONID=7mymobst47ig1s7uqy2z1fvx4
Host    localhost:8080
Referer http://localhost:8080/Di/tiles/entNews.htm
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1
X-Requested-With    XMLHttpRequest

Firebug - 来源

{"keys":[{"key":"canon","label":"Canon"},{"key":"ricoh","label":"Ricoh"}]}

Firebug - 回复

"NetworkError: 400 Bad Request - http://localhost:8080/Di/ajx/addKeys"

1 个答案:

答案 0 :(得分:12)

您正在发布JSON,而不是表单数据,但您尝试将ArrayList<Keys>作为表单参数进行阅读。

尝试从以下位置更改方法签名:

public ResponseEntity<String> addKeys(@RequestParam(value="keys") ArrayList<Keys> keys){

public ResponseEntity<String> addKeys(@RequestBody Keys[] keys){

这可能不起作用,因为您的JSON具有一个具有keys属性的对象,该属性是键列表。因此,您可以尝试将ajax发布数据更改为

data: JSON.stringify(tmpList)

这样您就可以发布列表而不是将其包装在另一个包含keys元素的对象中。