@RequestBody, @ResponseBody notes to understand

@RequestBody, @ResponseBody notes to understand

How his past did not pay attention too, to practice after the adoption of the front and rear ends of separate development mode, the front and rear end to get the notes are json format, this time @RequestBody, @ResponseBody two notes is very easy to use, the following details usage:

@RequestBody

1. Role:
  • body part of the data, using the system for reading the annotation request Request HttpMessageConverter parse the default configuration, then bind to the corresponding data on the object to return;
  • Binding HttpMessageConverter then returns to the object data in the controller parameter method.
2. Use the occasion:
GET, POST submission time, depending on the value of the request header Content-Type is determined:
  • application/x-www-form-urlencoded: Optional (i.e. not necessarily, since the data in this case @RequestParam, @ModelAttribute process may, of course, be able to handle @RequestBody);
  • multipart/form-data: Not treated ( i.e. @RequestBody using this format can not process data);
  • Other formats: must (other formats including application / json, application / xml data such as these formats must be processed @RequestBody.);
When the PUT submission, according to the request header Content-Type value to determine:
  • application/x-www-form-urlencoded: Must ;
  • multipart/form-data: Can not handle ;
  • Other formats: must ;
3. For example:

That is, if the data is json format, we want the argument passed is an object, it must be used @RequestBody.

@RequestMapping(value = "/test", Method = RequestMethod.POST, produces = "application/json;charset="UTF-8")
@ResponseBody
public JSONObject class Test(@RequestBody Test test) {
    String name = test.getName();
    // 将 name 回显
    Map<String, Object> map = new HashMap<>();
    map.put("name", name);
    JSONObject obj = JSONObject.fromObject(map);
    return obj;
}

@ResponseBody

1. Role:

The annotation for the Controller object returned by the method, by an appropriate body HttpMessageConverter conversion area after a specified data format, and writes the Response object.

2. Use the occasion:

Html page returned data is not the label, but some other data format (such as JSON, XML, etc.).

3. For example:
@RequestMapping(value = "/test", Method = RequestMethod.POST, produces = "application/json;charset="UTF-8")
@ResponseBody
public JSONObject class Test() {
    JSONObject obj = new JSONObject;
    obj.put("test", 1);
    // 将 obj 回显
    return obj;
}

reference:

https://blog.csdn.net/walkerJong/article/details/7520896

Finish.

Guess you like

Origin www.cnblogs.com/weixuqin/p/11373402.html