JSON-Spring MVC:如何将json数据发布到Spring MVC控制器 [英] JSON - Spring MVC : How to post json data to spring MVC controller

查看:108
本文介绍了JSON-Spring MVC:如何将json数据发布到Spring MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将JSON数据从jsp发送到controller时遇到问题.每次尝试时,我都会收到ajax错误Bad Request.我对JSON非常陌生,我真的不知道自己在做什么错.我搜索并尝试了一些可以在此站点找到的示例,但是我仍然遇到问题.

I have a problem posting JSON data from jsp to controller. Everytime I try I get an ajax error Bad Request. Im so new to JSON and I really don't know what I am doing wrong. I searched and tried some samples I can find in this site but still Im having a problem.

在我的控制器中:

@RequestMapping (method = RequestMethod.POST, headers ={"Accept=application/json"}, value = "/form")
public String postJournalEntry (@RequestParam ("json") String json, Model model) {
    System.out.println(json);
    return "successfullySaved";
}

在我的jsp中:

$("#btnPostGlEntry").click(function () {
    var glEntries = '{"glEntries":[{"generalLedgerId":"1"},{"accountId":"4"},{"amount":"344.44"},{"description":"Test Entry"},{"debit":"Yes"}]}';
    $.ajax({
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        url: contextPath + "/generalLedger/journalEntries/form",
        data : JSON.stringify(glEntries),
        success: function(data) {
            alert("Success!!!");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR + " : " + textStatus + " : " + errorThrown);
        }
    });
});

注意:我什至不确定控制器中的功能是否正确.我认为我的控制器和我的Ajax是错误的.请帮忙.

NOTE : Im not even sure if my function in my controller is correct. I think my controller and my ajax are wrong. Please help.

推荐答案

如果您希望将JSON反序列化为某个类,则必须定义这样的方法(并且不要忘记像以前一样添加jsonConverter答案):

If you want your JSON to be deserialized into some class, than you have to define method like this (and don't forget to add jsonConverter, as in previous answer):

.... method(@RequestBody MyClass data){ ... }

但是,如果您想让您的方法接受JSON作为String,则可以这样做:

But, if you want your method to accept JSON as String than do this:

.... method(@RequestBody String json){ ... }

因此,基本上,如果您发布JSON,则意味着JSON不是参数,而是请求的主体.最后,您必须使用@RequestBody注释,而不是@RequestParam.

So, basically, if you post JSON, it means that JSON is not a parameter, it is body of the request. And eventually you have to use @RequestBody annotation, instead of @RequestParam.

您可以在此处找到Spring Mvc和JSON的精美视频教程: sites.google.com/site /upida4j/example

You can find beautifull video tutorial of Spring Mvc and JSON here: sites.google.com/site/upida4j/example

这篇关于JSON-Spring MVC:如何将json数据发布到Spring MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆