注解@RequestMapping中的produces,consumes属性

今天在项目中看到了@RequestMapping中有两个属性,consumes和produces,于是就想弄清楚这两个属性是干什么的。

本来想贴自己项目的代码,但是公司比较严格,所以不贴了

一、produces

指定返回值类型,并且可以设置返回值类型和返回值的字符编码;

demo

/**属性produces="application/json"时,返回json数据*/
@Controller    
@RequestMapping(value = "/{path}", method = RequestMethod.GET, produces="application/json")    
public Object permissionGet(@PathVariable String path, @MyParameter PermissionTransRQ permissionTransRQ) {       
    //实现自己的逻辑调用
    return null;
}    

/**属性produces="MediaType.APPLICATION_JSON_VALUE;charset=utf-8"时,设置返回数据的字符编码为utf-8*/
@Controller    
@RequestMapping(value = "/{path}", method = RequestMethod.GET, produces="MediaType.APPLICATION_JSON_VALUE;charset=utf-8")    
public Object permissionGet(@PathVariable String path, @MyParameter PermissionTransRQ permissionTransRQ) {       
    //实现自己的逻辑调用
    return null;
}   

特别说明:produces="application/json"和注解@ResponseBody是一样的效果,使用了注解其实可以不使用该属性了。

二、consumes

指定处理请求当中的提交内容类型(Content-Type):application/json, text/html等;

demo

@Controller  
@RequestMapping(value = "/{path}", method = RequestMethod.POST, consumes="application/json")  
public Object permissionPost(@PathVariable String path, @RequestBody PermissionTransRQ permissionTransRQ) {      
    //实现自己的逻辑调用
    return null;
}  
原文地址:https://www.cnblogs.com/houchen/p/14183417.html