1、含义
1.1 produces
produces为@requestMapping注解里的属性项,其作用是指定返回值类型,不仅可设置返回值类型,还可设定返回值的字符编码。
1.2 consumes
consumes为@requestMapping的另一种属性,其用来指定处理请求的提交内容类型,例如application/json, text/html。
2、实例
2.1 produces
- 返回json数据,其实如下代码可省略produces属性,因已使用的@responseBody就是返回json数据,
@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
// get方法不安全,若涉及参数等敏感信息,请使用post方法将其放入请求体
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
}
- 返回json数据,并将其字符编码设置为 utf-8
@Controller
@RequestMapping(value = "/pets/{petId}", produces="MediaType.APPLICATION_JSON_VALUE;charset=utf-8")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
}
2.2 consumes
- 所能处理的request Content-Type必须为“application/json”类型请求,代码如下:
@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {
// implementation omitted
}