Ajax json POST和Spring MVC Controller

时间:2022-08-03 18:02:49

I have ajax json POST method like this

我有像这样的ajax json POST方法

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

XMLHttpRequest无法加载localhost:8080 / webeditor / spring / json /。仅支持HTTP的跨源请求。

I'm not sure how to correct above error.

我不确定如何纠正上述错误。

6 个解决方案

#1


5  

My final work version

我的最终作品版本

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

AJAX, and

AJAX,和

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

#2


2  

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

用Spring传递JSON是相当简单的。考虑以下jQuery函数:

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

现在使用以下String @Controller方法...

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

在我的情况下,请求是如此简单,我只是在控制器方法中硬连接json格式,但你可以像使用像Jackson这样的库来生成json字符串。

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

另外,正如其他人所说,验证@RequestMapping中的“值”是唯一的合法文件名。使用上面显示的json方法,您不必拥有相应的jsp页面(实际上它不会使用一个)。

#3


0  

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

在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

webeditor必须是战争名称或服务名称所以在你@RequestMapping(value =“/ webeditor / spring / json /”我认为你不应该'webeditor'它必须只是/ spring / json

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

通常404表示URL请求错误或者没有为该URL运行此类服务

#4


0  

Looks like jQuery so why not try

看起来像jQuery所以为什么不尝试

$.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映射

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

#5


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:

您的应用程序应该有一个上下文根,它将位于URL路径的其余部分之前。您还应该在web.xml中定义一个servlet-mapping,它定义了哪些请求被定向到Spring控制器。因此,如果您的应用程序的上下文根是“myapp”而您的servlet映射是* .html,那么您的ajax调用将如下所示:

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

#6


-1  

In yr jsp include the tag library like so

在你的jsp包括像这样的标签库

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

Then create a full url using spring

然后使用spring创建一个完整的URL

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

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

然后基于此创建javascript变量,以便您可以在Ajax中使用

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

No use the javascriptvariable representing the url :

不使用代表url的javascript变量:

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

#1


5  

My final work version

我的最终作品版本

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

AJAX, and

AJAX,和

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

#2


2  

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

用Spring传递JSON是相当简单的。考虑以下jQuery函数:

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

现在使用以下String @Controller方法...

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

在我的情况下,请求是如此简单,我只是在控制器方法中硬连接json格式,但你可以像使用像Jackson这样的库来生成json字符串。

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

另外,正如其他人所说,验证@RequestMapping中的“值”是唯一的合法文件名。使用上面显示的json方法,您不必拥有相应的jsp页面(实际上它不会使用一个)。

#3


0  

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

在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

webeditor必须是战争名称或服务名称所以在你@RequestMapping(value =“/ webeditor / spring / json /”我认为你不应该'webeditor'它必须只是/ spring / json

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

通常404表示URL请求错误或者没有为该URL运行此类服务

#4


0  

Looks like jQuery so why not try

看起来像jQuery所以为什么不尝试

$.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映射

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

#5


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:

您的应用程序应该有一个上下文根,它将位于URL路径的其余部分之前。您还应该在web.xml中定义一个servlet-mapping,它定义了哪些请求被定向到Spring控制器。因此,如果您的应用程序的上下文根是“myapp”而您的servlet映射是* .html,那么您的ajax调用将如下所示:

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

#6


-1  

In yr jsp include the tag library like so

在你的jsp包括像这样的标签库

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

Then create a full url using spring

然后使用spring创建一个完整的URL

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

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

然后基于此创建javascript变量,以便您可以在Ajax中使用

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

No use the javascriptvariable representing the url :

不使用代表url的javascript变量:

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