zoukankan      html  css  js  c++  java
  • Posting JSON to Spring MVC Controller

    Spring MVC can be setup to automatically bind incoming JSON string into a Java object. Firstly, ensure you have jackson-mapper-asl included on the classpath:

    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>

    Assuming the JSON string we want to bind represent a person object like this:

    {
      name: "Gerry",
      age: 20,
      city: "Sydney"
    }

    Which will be bound into following Java class:

    public class Person {
      private String name;
      private int age;
      private String city;
      // getters & setters ...
    }

    Declare the Spring MVC controller handler method like below. The handler method is mapped into path “addPerson” with method POST.

    @RequestMapping(value = "/addPerson", 
                    method = RequestMethod.POST,
                    headers = {"Content-type=application/json"})
    @ResponseBody
    public JsonResponse addPerson(@RequestBody Person person) {
      logger.debug(person.toString());
      return new JsonResponse("OK","");
    }

    Also pay attention to @ResponseBody and the returned JsonResponse object. Here JsonResponse is a class to return the result of the addPerson operation.

    public class JsonResponse {
     
      private String status = "";
      private String errorMessage = "";
     
      public JsonResponse(String status, String errorMessage) {
        this.status = status;
        this.errorMessage = errorMessage;
      }
    }

    When converted to JSON this will look like this:

    {
      status : "OK",
      errorMessage : ""
    }

    Below is an example jQuery based javascript handler that posts into the above Spring MVC handler and observe the returned value:

    $.ajax({
      type: "POST",
      url: "addPerson",
      data: JSON.stringify({ name: "Gerry", age: 20, city: "Sydney" }),
      contentType: 'application/json',
      success: function(data) {
        if(data.status == 'OK') alert('Person has been added');
        else alert('Failed adding person: ' + data.status + ', ' + data.errorMessage);
      }
    });
  • 相关阅读:
    双色球的概率和收益
    伽玛函数
    概率统计13——二项分布与多项分布
    贝叶斯决策理论(1)
    线性代数笔记34——左右逆和伪逆
    线性代数笔记33——基变换和图像压缩
    线性代数笔记32——线性变换及对应矩阵
    线性代数笔记31——奇异值分解
    线性代数笔记30——相似矩阵和诺尔当型
    线性代数笔记29——正定矩阵和最小值
  • 原文地址:https://www.cnblogs.com/sos-blue/p/5101559.html
Copyright © 2011-2022 走看看