passing JSON data to a Spring MVC controller

前端 未结 3 1612
我在风中等你
我在风中等你 2020-12-02 10:48

I need to send a JSON string to Spring MVC controller.But I do not have any form bindings to it , I just need to send a plain JSON data to Controller class.I am making jQu

3条回答
  •  情书的邮戳
    2020-12-02 11:03

    Add the following dependencies

    
        org.codehaus.jackson 
        jackson-mapper-asl
        1.9.7
    
    
    
        org.codehaus.jackson 
        jackson-core-asl
        1.9.7
    
    

    Modify request as follows

    $.ajax({ 
        url:urlName,    
        type:"POST", 
        contentType: "application/json; charset=utf-8",
        data: jsonString, //Stringified Json Object
        async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
        cache: false,    //This will force requested pages not to be cached by the browser          
        processData:false, //To avoid making query String instead of JSON
        success: function(resposeJsonObject){
            // Success Message Handler
        }
    });
    

    Controller side

    @RequestMapping(value = urlPattern , method = RequestMethod.POST)
    public @ResponseBody Person save(@RequestBody Person jsonString) {
    
       Person person=personService.savedata(jsonString);
       return person;
    }
    

    @RequestBody - Covert Json object to java
    @ResponseBody- convert Java object to json

提交回复
热议问题