Home>

This article introduces the method of receiving json data by spring mvc through code examples.The details are as follows:

Receive json

With @requestbody annotation, the front end only needs to submit a formatted json to the controller, and spring will automatically assemble it into a bean.

1) On the basis of using the first way to process the returned json in the above project,Add the following methods:

java code

 @requestmapping (value="/add", method=requestmethod.post, headers={"content-type=application/json", "content-type=application/xml"})
  @responsebody
  public object adduser (@requestbody user user)
  {
    system.out.println (user.getname () + "" + user.getage ());
    return new hashmap<string, string>(). put ("success", "true");
  }

The pojo here is as follows:

java code

 public class user {
    private string name;
    private string age;
    //getter setter
  }

2) While at the front desk,We can use jquery to process json. From here, I got a jquery plugin that returns data from a form as a json object:

js code

$.fn.serializeobject=function () {
    var o=();
    var a=this.serializearray ();
    $.each (a, function () {
      if (o [this.name]) {
        if (! o [this.name] .push) {
          o [this.name]=[o [this.name]];
        }
        o [this.name] .push (this.value || "");
      }
      else {
        o [this.name]=this.value || "";
      }
    });
    return o;
  };

Here is the code to receive and send json using jquery:

js code

$(document) .ready (function () {
    jquery.ajax ({
      type:"get",      contenttype:"application/json",      url:"jsonfeed.do",      datatype:"json",      success:function (data) {
        if (data &&data.status == "0") {
          $.each (data.data, function (i, item) {
            $("#info"). append ("Name:" + item.name + ", Age:" + item.age);
          });
        }
      },      error:function () {
        alert ("error")
      }
    });
    $("#submit"). click (function () {
      var jsonuserinfo=$.tojson ($("#form"). serializeobject ());
      jquery.ajax ({
        type:"post",        contenttype:"application/json",        url:"add.do",        data:jsonuserinfo,        datatype:"json",        success:function (data) {
          alert ("Added successfully!");
        },        error:function () {
          alert ("error")
        }
      });
    });
  });

But it seems that using spring is really a troublesome thing,Relative to Jersey's implementation of restful,There are indeed a lot of inconveniences.

The above is the relevant information of spring mvc receiving json data shared by everyone in this article.Hope you like it.

  • Previous Example of modifying PHP script to make WordPress block spam comments
  • Next Use PHP script in WordPress to determine what country your visitors are from