i am trying to post data though ajax post to spring controller. My ajax code is
function postData(tag){
console.debug(tag);
var targetUrl = "/add/tag";
$.ajax({
url : targetUrl,
type : "POST",
data : tag,
dataType : "text",
success : function(response){
console.debug(response);
},
error : function(){
console.debug("error : ".concat(response));
}
});
}
and my controller code is
@RequestMapping(value = "/add/tag", method = POST, consumes = { "application/json" },headers = "content-type=application/x-www-form-urlencoded")
@ResponseBody
public Integer addTag(HttpServletRequest request,
@PathVariable("uid") String gatheringUid, @RequestBody String tag) {
System.out.print(tag);
return gatheringService.updateGathering(gatheringUid, tags);
}
on server side it prints the value of tag appended by "=" sign, while on firebug console value prints as i enterd.
For example when i post data "test", on firebug console it prints "test" and on server side console it prints "test=".
Can any one kindly tell me what is the problem here.
Thanks in advance, regards.
This is a consequence of AJAX sending your POST with a content-type of application/x-www-form-urlencoded
.
Spring uses a StringHttpMessageConverter
to resolve the argument to bind to a @RequestBody
annotated String
parameter. Internally, this checks if the request was a form POST. If it is, it deserializes the whole body as if it was a form submission. In this case, a single word text
, appears as if it was, for example, a single <input>
element with no value, ie. text=
.
If you're curious, this is done in ServletServerHttpRequest#getBodyFromServletRequestParameters(..)
.
Change your content-type to something more appropriate, maybe text/plain
. Don't use dataType
. Use contentType
or the headers
.
FYI, based on Sotirios' answer, the following worked in the Ajax jQuery code.
$.ajax({
type : "post",
dataType : 'json',
contentType : 'text/plain', // This was added to delete the =
url : 'myURL',
data : id
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With