Ajax json POST和Spring MVC Controller

时间:2012-07-06 11:56:30

标签: java ajax spring spring-mvc

我有像这样的ajax json POST方法

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

处理发布请求的控制器

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

}

但我收到此错误

  

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

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

6 个答案:

答案 0 :(得分:5)

我的最终作品版本     

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

AJAX和

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

答案 1 :(得分:2)

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

现在使用以下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);
}

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

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

答案 2 :(得分:0)

在网址:url:“localhost:8080 / webeditor / spring / json /”

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

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

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

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

如果您想要跨域请求,请执行以下操作: -

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

并添加servlet映射

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

答案 5 :(得分:-1)

在jr中包含像这样的标记库

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

然后使用spring

创建一个完整的URL
<c:url var="yourFullUrl" value="/webeditor/spring/json/" />

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

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

不使用代表网址的javascript变量:

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