8

我在这个 POST 请求上收到 400 错误请求。知道这里有什么问题吗?日志在这里

控制器

@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>

阿贾克斯

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'
});

萤火虫 - 网址

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

萤火虫-来源

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

Firebug - 响应

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

1 回答 1

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 元素的对象中。

于 2012-10-25T18:57:25.550 回答