400 Bad Request for Spring JQuery Ajax Post

I get 400 bad requests for this POST request. Think what the problem is? Magazines are here .

controller

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

context-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 - URL

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

Firebug - response headers

 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 - request headers

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

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

Firebug - Response

 "NetworkError: 400 Bad Request - http://localhost:8080/Di/ajx/addKeys" 
+7
jquery spring-mvc
source share
1 answer

You are posting JSON, not generating data, but you are trying to read ArrayList<Keys> as a form parameter.

Try changing the method signature from:

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

to

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

This may not work, since your JSON has an object with the keys attribute, which is a list of keys. So you can try changing your ajax post data to something like

 data: JSON.stringify(tmpList) 

so that you just send the list instead of wrapping it with another object that has the keys element.

+10
source share

All Articles