jQuery 将 JSON 数据传递给 Spring MVC 控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18524524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:51:34  来源:igfitidea点击:

passing JSON data to a Spring MVC controller

jsonjqueryspring-mvccontroller

提问by user2702205

I need to send a JSON string to Spring MVC controller.But I do not have any form bindings to it , I just need to send a plain JSON data to Controller class.I am making jQuery AJAX call to the Controller method like the below code.

我需要向 Spring MVC 控制器发送一个 JSON 字符串。但是我没有任何形式绑定到它,我只需要向控制器类发送一个普通的 JSON 数据。我正在对控制器方法进行 jQuery AJAX 调用,如下面的代码.

$.ajax ({
    url: "./save",
    type: "POST",
    data: JSON.stringify(array),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(){
        alert("success ");
    }
});

But how do I retrieve it in the Controller method?(Note: It is just plain JSON data and not a form submission).

但是如何在 Controller 方法中检索它?(注意:它只是普通的 JSON 数据而不是表单提交)。

回答by Vineeth Bhaskaran

Add the following dependencies

添加以下依赖项

<dependency>
    <groupId>org.codehaus.Hymanson</groupId> 
    <artifactId>Hymanson-mapper-asl</artifactId>
    <version>1.9.7</version>
</dependency>

<dependency>
    <groupId>org.codehaus.Hymanson</groupId> 
    <artifactId>Hymanson-core-asl</artifactId>
    <version>1.9.7</version>
</dependency>

Modify request as follows

修改请求如下

$.ajax({ 
    url:urlName,    
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser          
    processData:false, //To avoid making query String instead of JSON
    success: function(resposeJsonObject){
        // Success Message Handler
    }
});

Controller side

控制器端

@RequestMapping(value = urlPattern , method = RequestMethod.POST)
public @ResponseBody Person save(@RequestBody Person jsonString) {

   Person person=personService.savedata(jsonString);
   return person;
}

@RequestBody- Covert Json object to java
@ResponseBody- convert Java object to json

@RequestBody- 将 Json 对象
@ResponseBody转换为 Java - 将 Java 对象转换为 json

回答by surya handoko

  1. Html

    $('#save').click(function(event) {        
        var jenis = $('#jenis').val();
        var model = $('#model').val();
        var harga = $('#harga').val();
        var json = { "jenis" : jenis, "model" : model, "harga": harga};
        $.ajax({
            url: 'phone/save',
            data: JSON.stringify(json),
            type: "POST",           
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(data){ 
                alert(data);
            }
        });
    
        event.preventDefault();
    });
    
    1. Controller

      @Controller
      @RequestMapping(value="/phone")
      public class phoneController {
      
          phoneDao pd=new phoneDao();
      
          @RequestMapping(value="/save",method=RequestMethod.POST)
          public @ResponseBody
          int save(@RequestBody Smartphones phone)
          {
              return pd.save(phone);
          }
      
    2. Dao

      public Integer save(Smartphones i) {
          int id = 0;
          Session session=HibernateUtil.getSessionFactory().openSession();
          Transaction trans=session.beginTransaction();
          try {
              session.save(i);   
              id=i.getId();
              trans.commit();
          }
          catch(HibernateException he){}
          return id;
      }
      
  1. html

    $('#save').click(function(event) {        
        var jenis = $('#jenis').val();
        var model = $('#model').val();
        var harga = $('#harga').val();
        var json = { "jenis" : jenis, "model" : model, "harga": harga};
        $.ajax({
            url: 'phone/save',
            data: JSON.stringify(json),
            type: "POST",           
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(data){ 
                alert(data);
            }
        });
    
        event.preventDefault();
    });
    
    1. 控制器

      @Controller
      @RequestMapping(value="/phone")
      public class phoneController {
      
          phoneDao pd=new phoneDao();
      
          @RequestMapping(value="/save",method=RequestMethod.POST)
          public @ResponseBody
          int save(@RequestBody Smartphones phone)
          {
              return pd.save(phone);
          }
      
    2. public Integer save(Smartphones i) {
          int id = 0;
          Session session=HibernateUtil.getSessionFactory().openSession();
          Transaction trans=session.beginTransaction();
          try {
              session.save(i);   
              id=i.getId();
              trans.commit();
          }
          catch(HibernateException he){}
          return id;
      }
      

回答by Leonardo Silva

You can stringify the JSON Object with JSON.stringify(jsonObject) and receive it on controller as String.

您可以使用 JSON.stringify(jsonObject) 对 JSON 对象进行字符串化,并在控制器上将其作为字符串接收。

In the Controller, you can use the javax.jsonto convert and manipulate this.

在控制器中,您可以使用javax.json来转换和操作它。

Download and add the .jar to the project libs and import the JsonObject.

下载 .jar 并将其添加到项目库中并导入 JsonObject。

To create an json object, you can use

要创建一个 json 对象,您可以使用

JsonObjectBuilder job = Json.createObjectBuilder();
job.add("header1", foo1);
job.add("header2", foo2);
JsonObject json = job.build();

To read it from String, you can use

要从字符串中读取它,您可以使用

JsonReader jr = Json.createReader(new StringReader(jsonString));
JsonObject json = jsonReader.readObject();
jsonReader.close();