Search code examples
jqueryajaxspringmodelattribute

JQuery AJAX strange behaviour with parameters (Spring's @ModelAttribute)


I'm trying to pass a Map< String, String> to Spring via Ajax using @ModelAttribute notation. With IntelliJ's REST client, I just have to add the "infos[KEY]" param with value "VALUE" to get the corresponding key/value couple populated in the hashmap.

I'm trying to reproduce the same behaviour with JQuery

function update()
{
     $.ajax(
          {
            type: "PATCH",
            url: "url",
            dataType: "json",
            data: {"infos[TheAnswer]": "42"},
            success: function(data)
              {
                alert("OK");
              }
          });
}

But Spring controller can't get to populate my model. Here it is (but i shouldn't be the problem because as I said IntelliJ's REST client works fine)

public class ExtraInfos implements Serializable
{
    protected HashMap<String, String> infos = new HashMap<String, String>();

    public HashMap<String, String> getInfos()
    {
        return infos;
    }

    public void setInfos(HashMap<String, String> infos)
    {
        this.infos = infos;
    }
}

Here's my controller's method:

@RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
public
@ResponseBody
Contact updateContact(@PathVariable("id") Long id,
                      @ModelAttribute ExtraInfos infos)
{
    return this.service.update(id, infos);
 }

Solution

  • Well using this controller

    //Just an example

       @RequestMapping(value = "/test/{id}", method = RequestMethod.POST)
        public @ResponseBody Integer extra(@PathVariable("id") Long id, @RequestBody ExtraInfos extraInfos){
                System.out.println(id);
                System.out.println(extraInfos.getInfos());
    
                return 1;
            } 
    

    The thing here is as the other previously mentioned you need to send the object for ExtraInfos.

    If we suppose that this is an example value for ExtraInfos

    ExtraInfos = {infos:{"key":"value"}}
    

    Our mapper will create the ExtraInfos object with it.

    Doing this ajax call (in this case for this mapper).

    $.ajax({
        url:"test/23123",
        type:"post",
        contentType: "application/json; charset=utf-8",
        data:JSON.stringify(ExtraInfos)
    })
    

    Output on the console:

    23123
    {key=value}