Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajax post to spring mvc appends "=" sign to request data

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.

like image 581
Shahzeb Khan Avatar asked Feb 26 '14 06:02

Shahzeb Khan


2 Answers

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.

like image 87
Sotirios Delimanolis Avatar answered Sep 27 '22 18:09

Sotirios Delimanolis


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
     })
like image 24
gene b. Avatar answered Sep 27 '22 18:09

gene b.