passing JSON data to a Spring MVC controller

前端 未结 3 1603
我在风中等你
我在风中等你 2020-12-02 10:48

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 jQu

相关标签:
3条回答
  • 2020-12-02 10:55
    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;
        }
        
    0 讨论(0)
  • 2020-12-02 11:03

    Add the following dependencies

    <dependency>
        <groupId>org.codehaus.jackson</groupId> 
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.7</version>
    </dependency>
    
    <dependency>
        <groupId>org.codehaus.jackson</groupId> 
        <artifactId>jackson-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

    0 讨论(0)
  • 2020-12-02 11:22

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

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

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

    To create an json object, you can use

    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();
    
    0 讨论(0)
提交回复
热议问题