详解Http请求中Content-Type讲解以及在Spring MVC中的应用
引言: 在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息,但是却很少有人去全面了解content-type中允许的值有多少,这里将讲解Content-Type的可用值,以及在spring MVC中如何使用它们来映射请求信息。
1. Content-Type
MediaType,即是Internet Media Type,互联网媒体类型;也叫做MIME类型,在Http协议消息头中,使用Content-Type来表示具体请求中的媒体类型信息。
例如: Content-Type: text/html;charset:utf-8;
常见的媒体格式类型如下:
以application开头的媒体格式类型:
3.2 params的示例
@RequestMapping(value = "/test/{userId}", method = RequestMethod.GET, params="myParam=myValue") public void findUser(@PathVariable String userId) { // implementation omitted }仅处理请求中包含了名为“myParam”,值为“myValue”的请求,起到了一个过滤的作用。
3.3 consumes/produces
@Controller @RequestMapping(value = "/users", method = RequestMethod.POST, consumes="application/json", produces="application/json") @ResponseBody public List<User> addUser(@RequestBody User userl) { // implementation omitted return List<User> users; } 方法仅处理request Content-Type为“application/json”类型的请求. produces标识==>处理request请求中Accept头中包含了"application/json"的请求,同时暗示了返回的内容类型为application/json;
4. 总结
在本文中,首先介绍了Content-Type主要支持的格式内容,然后基于@RequestMapping标注的内容介绍了主要的使用方法,其中,headers, consumes,produces,都是使用Content-Type中使用的各种媒体格式内容,可以基于这个格式内容来进行访问的控制和过滤。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!