4

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.

6
  • You are returning void, no need to use response body Commented Jul 6, 2012 at 12:03
  • it did not solve my problem, it no mapping found for HTTP Commented Jul 6, 2012 at 12:19
  • no I didn;t think it would, just an observation. But this all looks fine, there is no request mapping on the class ? Commented Jul 6, 2012 at 12:21
  • thanks for this=) yeap, 404 PageNotFound - No mapping found for HTTP request Commented Jul 6, 2012 at 12:22
  • The method that this class is defined in, does that have a global request mapping - which is then prepended to the methods request mapping Commented Jul 6, 2012 at 12:26

6 Answers 6

5

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 );
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

0

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>

1 Comment

"<url-pattern>*.jsonp</url-pattern>" is it "jsonp" or "json"?
0

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

Comments

-1

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>

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.