Ajax json POST and Spring MVC Controller

37,642

Solution 1

My final work version

var jsonfile={json:JSON.stringify(contents)};
$.ajax({
    type: 'POST',
    url: "/webeditor/spring/json/", 
    data: jsonfile,
    dataType: "json"
});

AJAX, and

@RequestMapping(value = "/json/", method = RequestMethod.POST)
public void saveNewUsers( @RequestParam ("json") String json)
{
    System.out.println( json );
}

Solution 2

Passing JSON with Spring is fairly straight forward. Consider the following jQuery function:

function processUrlData(data, callback) {
    $.ajax({
        type: "GET",
        url: "getCannedMessageAsJson.html",
        data: data,
        dataType: "json",
        success: function(responseData, textStatus) {
            processResponse(responseData, callback);
        },
        error : function(responseData) {
            consoleDebug("  in ajax, error: " + responseData.responseText); 
        }
    });
}

Now use the following String @Controller method...

@RequestMapping(value = "/getCannedMessageAsJson.html", method = RequestMethod.POST) 
public ResponseEntity<String> getCannedMessageAsJson(String network, String status, Model model) {

    int messageId = service.getIpoeCannedMessageId(network, status);
    String message = service.getIpoeCannedMessage(network, status);

    message = message.replaceAll("\"", "&quot;");
    message = message.replaceAll("\n", "");

    String json = "{\"messageId\": \"" + messageId 
    + "\", \"message\": \"" + message + "\"}"; 

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}

In my case the request is so simple that I'm just hardwiring the json formatting in the controller method, but you could just as easily use a library like Jackson to produce the json string.

Also as others have stated, verify that the "value" in the @RequestMapping is a unique, legitimate filename. With the json method I show above you don't have to have a corresponding jsp page (in fact it won't use one).

Share:
37,642
Vlad Hudnitsky
Author by

Vlad Hudnitsky

Updated on July 31, 2022

Comments

  • Vlad Hudnitsky
    Vlad Hudnitsky almost 2 years

    I have ajax json POST method like this

    $.ajax({
        type: 'POST',
        url: "localhost:8080/webeditor/spring/json/", 
        data: JSON.stringify(contents),
        dataType: "json"
    });
    

    Controller to handle post request

    JSONPObject json;
    BindingResult result = new BeanPropertyBindingResult( json , "MyPresentation" );
    @RequestMapping(value="json/", method = RequestMethod.POST)
    public void savePresentationInJSON(Presentations presentation,BindingResult result) {
            //do some action
    
    }
    

    but I getting this error

    XMLHttpRequest cannot load localhost:8080/webeditor/spring/json/. Cross origin requests are only supported for HTTP.

    I'm not sure how to correct above error.

    • NimChimpsky
      NimChimpsky almost 12 years
      You are returning void, no need to use response body
    • Vlad Hudnitsky
      Vlad Hudnitsky almost 12 years
      it did not solve my problem, it no mapping found for HTTP
    • NimChimpsky
      NimChimpsky almost 12 years
      no I didn;t think it would, just an observation. But this all looks fine, there is no request mapping on the class ?
    • Vlad Hudnitsky
      Vlad Hudnitsky almost 12 years
      thanks for this=) yeap, 404 PageNotFound - No mapping found for HTTP request
    • NimChimpsky
      NimChimpsky almost 12 years
      The method that this class is defined in, does that have a global request mapping - which is then prepended to the methods request mapping
    • Vlad Hudnitsky
      Vlad Hudnitsky almost 12 years
      look, I edit ajax. but now I request new error :XMLHttpRequest cannot load localhost:8080/webeditor/spring/json/. Cross origin requests are only supported for HTTP.
  • NimChimpsky
    NimChimpsky almost 12 years
    you can't generate a spring based url in js alone, you have to do what I said (or a close variation of). JS is client side, you need server side processing for spring url. O ryou coul dhardcode th ehost
  • stallion
    stallion over 8 years
    "<url-pattern>*.jsonp</url-pattern>" is it "jsonp" or "json"?