produces在@requestMapping中的使用方式和作用

来源:互联网 发布:mac梦幻西游启动失败 编辑:程序博客网 时间:2024/06/09 18:53

produces可能不算一个注解,因为什么呢,它是注解@requestMapping注解里面的属性项,

它的作用是指定返回值类型,不但可以设置返回值类型还可以设定返回值的字符编码

还有一个属性与其对应,就是consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

他们的使用方法如下:

一、produces的例子

produces第一种使用,返回json数据,下边的代码可以省略produces属性,因为我们已经使用了注解@responseBody就是返回值是json数据:

[html] view plain copy
print?
  1. @Controller    
  2. @RequestMapping(value = “/pets/{petId}”method = RequestMethod.GET, produces=“application/json”)    
  3. @ResponseBody    
  4. public Pet getPet(@PathVariable String petId, Model model) {       
  5.     // implementation omitted    
  6. }    
@Controller  @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")  @ResponseBody  public Pet getPet(@PathVariable String petId, Model model) {         // implementation omitted  }  

produces第二种使用,返回json数据的字符编码为utf-8.:
[html] view plain copy
print?
  1. @Controller    
  2. @RequestMapping(value = “/pets/{petId}”produces=”<span style=”font-family: “Courier New”, monospace; white-space: pre; background-color: rgb(247, 247, 247);”><strong><span style=“color:#ff0000;”>MediaType.APPLICATION_JSON_VALUE”+”;charset=utf-8</span></strong></span>)    
  3. @ResponseBody    
  4. public Pet getPet(@PathVariable String petId, Model model) {        
  5.     // implementation omitted    
  6. }    
@Controller  @RequestMapping(value = "/pets/{petId}", produces="MediaType.APPLICATION_JSON_VALUE"+";charset=utf-8")  @ResponseBody  public Pet getPet(@PathVariable String petId, Model model) {          // implementation omitted  }  

二、consumes的例子(方法仅处理request Content-Type为“application/json”类型的请求。

  1. @Controller  
  2. @RequestMapping(value = “/pets”, method = RequestMethod.POST, consumes=“application/json”)  
  3. public void addPet(@RequestBody Pet pet, Model model) {      
  4.     // implementation omitted  
  5. }  

原创粉丝点击