Vlad Hudnitsky
Vlad Hudnitsky

Reputation: 1353

Ajax json POST and Spring MVC Controller

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.

Upvotes: 4

Views: 37854

Answers (6)

GriffeyDog
GriffeyDog

Reputation: 8386

Your application should have a context root, which would precede the rest of your URL path. And you should also have a servlet-mapping defined in web.xml which defines which requests get directed to your Spring controllers. So if the context root of your application is "myapp" and your servlet-mapping is going to *.html, then your ajax call would look like this:

$.ajax({
    type: 'POST',
    url: "/myapp/webeditor/spring/json.html",
    data: JSON.stringify(contents),
    dataType: "json",
    success: function(response) {
        // Success Action
    }
}); 

Upvotes: 0

Vlad Hudnitsky
Vlad Hudnitsky

Reputation: 1353

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 );
}

Upvotes: 5

MikePatel
MikePatel

Reputation: 2672

Looks like jQuery so why not try

$.getJSON('webeditor/spring/json', JSON.stringify(contents, function(data) {//do callbackstuff});

If you wanted to request cross domain the way to do it is like :-

cbFn = function(data) {
   // do callback stuff. 
}

    var ca = document.createElement('script');
                ca.type = 'text/javascript';
                ca.async = true;
                ca.src = server + '/webeditor/spring/json.jsonp?callback=cbFn';
                var s = document.getElementsByTagName('head')[0];
                s.parentNode.insertBefore(ca, s);

and also add the servlet mapping

<servlet-mapping>
    <servlet-name>yourSevletName</servlet-name>
    <url-pattern>*.jsonp</url-pattern>
</servlet-mapping>

Upvotes: 0

Bill
Bill

Reputation: 2633

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).

Upvotes: 2

user1407870
user1407870

Reputation: 9

In the URL : url: "localhost:8080/webeditor/spring/json/"

webeditor must be war name or service name so in ur @RequestMapping(value="/webeditor/spring/json/" i think u should not have 'webeditor' it must be only /spring/json

normally 404 means the for the URL requst is wrong or no such service is running for that URL

Upvotes: 0

NimChimpsky
NimChimpsky

Reputation: 47300

In yr jsp include the tag library like so

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Then create a full url using spring

<c:url var="yourFullUrl" value="/webeditor/spring/json/" />

then create javascript variable based on this so you can use in Ajax

<script>
var yourUrl= '<c:out value="${yourFullUrl}"/>';
</script>

No use the javascriptvariable representing the url :

<script>
$.ajax({
        type: 'POST',
        url: yourUrl, 
        data: JSON.stringify(contents),
        dataType: "json"
});
</script>

Upvotes: -1

Related Questions