Ajax json POST和Spring MVC控制器

4
我有一个像这样的Ajax JSON POST方法:
$.ajax({
    type: 'POST',
    url: "localhost:8080/webeditor/spring/json/", 
    data: JSON.stringify(contents),
    dataType: "json"
});

处理POST请求的控制器

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。

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


你正在返回void,不需要使用响应体。 - NimChimpsky
它没有解决我的问题,HTTP没有找到映射。 - Vlad Hudnitsky
没有,我不认为会有,这只是一个观察。但是这一切看起来都很好,类上没有请求映射吗? - NimChimpsky
感谢这个=)是的,404页面未找到 - 没有映射HTTP请求。 - Vlad Hudnitsky
这个类定义的方法中,是否有一个全局请求映射(Global Request Mapping) - 然后将其添加到该方法的请求映射前面? - NimChimpsky
看起来,我正在编辑Ajax。但现在我收到了新的错误:XMLHttpRequest无法加载localhost:8080/webeditor/spring/json/。跨域请求仅支持HTTP。 - Vlad Hudnitsky
6个回答

5

我的最终工作版本

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

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

现在使用以下字符串 @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中的"value"是否是唯一的、合法的文件名。使用上述的json方法,您不需要相应的jsp页面(实际上它不会使用任何一个)。

0
在URL中:url:"localhost:8080/webeditor/spring/json/"
webeditor必须是war名称或服务名称,因此在您的@RequestMapping(value="/webeditor/spring/json/"中,我认为您不应该有'webeditor',它必须只是/spring/json 通常404意味着URL请求错误或没有针对该URL运行此类服务。

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

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>

"<url-pattern>*.jsonp</url-pattern>" 是 "jsonp" 还是 "json"? - stallion

-1
在您的 JSP 中添加标签库,如下所示:
<%@ 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>

不要使用代表URL的javascript变量:

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

你不能仅使用JS生成基于Spring的URL,你必须按照我说的方式(或类似方式)进行操作。JS是客户端语言,你需要服务器端处理Spring URL。或者你可以硬编码主机。 - NimChimpsky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接