码农小汪-Spring MVC -生产者、消费者限定 Content-Type Accept

来源:互联网 发布:mp4相册制作软件 编辑:程序博客网 时间:2024/06/07 02:23

首先让我们看一下通过HTTP协议传输的媒体类型及如何表示媒体类型:

Media Type
互联网媒体类型,一般就是我们所说的MIME类型,用来确定请求的内容类型或响应的内容类型。

媒体类型格式:type/subtype(;parameter)?
type主类型,任意的字符串,如text,如果是*号代表所有;
subtype 子类型,任意的字符串,如html,如果是*号代表所有;
parameter 可选,一些参数,如Accept请求头的q参数, Content-Type的 charset参数。

常见媒体类型:

text/html : HTML格式 text/plain :纯文本格式 text/xml :XML格式
image/gif :gif图片格式 image/jpeg :jpg图片格式 image/png:png图片格式

application/x-www-form-urlencoded : < form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)。
multipart/form-data : 当你需要在表单中进行文件上传时,就需要使用该格式;

application/xhtml+xml :XHTML格式 application/xml : XML数据格式
application/atom+xml :Atom XML聚合格式 application/json : JSON数据格式
application/pdf :pdf格式 application/msword : Word文档格式
application/octet-stream : 二进制流数据(如常见的文件下载)。

在如tomcat服务器的 “conf/web.xml”中指定了扩展名到媒体类型的映射,在此我们可以看到服务器支持的媒体类型。

Content-Type:内容类型,即请求/响应的内容区数据的媒体类型;

    @RequestMapping(value = "/ContentType", method = RequestMethod.GET)    public String showForm() throws IOException {        //form表单,使用application/x-www-form-urlencoded编码方式提交表单        return "consumesproduces/Content-Type";    }    @RequestMapping(value = "/ContentType", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")    public String request1(HttpServletRequest request) throws IOException {        //①得到请求的内容区数据的类型        String contentType = request.getContentType();         System.out.println("========ContentType:" + contentType);        //②得到请求的内容区数据的编码方式,如果请求中没有指定则为null        //注意,我们的CharacterEncodingFilter这个过滤器设置了编码(UTF-8)        //编码只能被指定一次,即如果客户端设置了编码,则过滤器不会再设置        String characterEncoding = request.getCharacterEncoding();        System.out.println("========CharacterEncoding:" + characterEncoding);        //③表示请求的内容区数据为form表单提交的参数,此时我们可以通过request.getParameter得到数据(key=value)        System.out.println(request.getParameter("realname"));        System.out.println(request.getParameter("username"));        return "success";    }

这里写图片描述

①客户端—发送请求—服务器:客户端通过请求头Content-Type指定内容体的媒体类型(即客户端此时是生产者),服务器根据Content-Type消费内容体数据(即服务器此时是消费者);
②服务器—发送请求—客户端:服务器生产响应头Content-Type指定的响应体数据(即服务器此时是生产者),客户端根据Content-Type消费内容体数据(即客户端此时是消费者)。

问题:
①服务器端可以通过指定【headers = “Content-Type=application/json”】来声明可处理(可消费)的媒体类型,即只消费Content-Type指定的请求内容体数据;
②客户端如何告诉服务器端它只消费什么媒体类型的数据呢?即客户端接受(需要)什么类型的数据呢?服务器应该生产什么类型的数据?此时我们可以请求的Accept请求头来实现这个功能。

Accept:用来指定什么媒体类型的响应是可接受的,即告诉服务器我需要什么媒体类型的数据,此时服务器应该根据Accept请求头生产指定媒体类型的数据。

服务器端控制器

    @RequestMapping(value = "/response/ContentType", headers = "Accept=application/json")    public void response2(HttpServletResponse response) throws IOException {        //①表示响应的内容区数据的媒体类型为json格式,且编码为utf-8(客户端应该以utf-8解码)        response.setContentType("application/json;charset=utf-8");        //②写出响应体内容        String jsonData = "{\"username\":\"zhang\", \"password\":\"123\"}";        response.getWriter().write(jsonData);    }

使用普通客户端测试(服务器之间通信可使用该方式)

    private static void jsonRequest() throws IOException, URISyntaxException {        //请求的地址        String url = "http://localhost:9080/springmvc-chapter6/response/ContentType";        //①创建Http Request(内部使用HttpURLConnection)        ClientHttpRequest request =             new SimpleClientHttpRequestFactory().                   createRequest(new URI(url), HttpMethod.POST);        //②设置客户端可接受的媒体类型(即需要什么类型的响应体数据)        request.getHeaders().set("Accept", "application/json");                //③发送请求并得到响应        ClientHttpResponse response = request.execute();        //④得到响应体的编码方式        Charset charset = response.getHeaders().getContentType().getCharSet();                //⑤得到响应体的内容                InputStream is = response.getBody();        byte bytes[] = new byte[(int)response.getHeaders().getContentLength()];        is.read(bytes);        String jsonData = new String(bytes, charset);        System.out.println("charset : " + charset + ", json data : " + jsonData);    }

生产者消费者流程图

这里写图片描述
请求阶段:客户端是生产者【生产Content-Type媒体类型的请求内容区数据】,服务器是消费者【消费客户端生产的Content-Type媒体类型的请求内容区数据】;
响应阶段:服务器是生产者【生产客户端请求头参数Accept指定的响应体数据】,客户端是消费者【消费服务器根据Accept请求头生产的响应体数据】。

如上生产者/消费者写法无法很好的体现我们分析的生产者/消费者模式,Spring3.1为生产者/消费者模式提供了简化支持,接下来我们学习一下如何在Spring3.1中来实现生产者/消费者模式吧。

Spring3.1开始支持消费者、生产者限定,而且必须使用如下HandlerMapping和HandlerAdapter才支持:

<!--Spring3.1开始的注解 HandlerMapping --><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <!--Spring3.1开始的注解 HandlerAdapter --><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> 

一、功能处理方法是消费者
@RequestMapping(value = “/consumes”, consumes = {“application/json”}):此处使用consumes来指定功能处理方法能消费的媒体类型,其通过请求头的“Content-Type”来判断。

此种方式相对使用@RequestMapping的“headers = “Content-Type=application/json””更能表明你的目的。

服务器控制器代码详解cn.javass.chapter6.web.controller.consumesproduces.ConsumesController;
客户端代码类似于之前的Content-Type中的客户端,详见ConsumesClient.Java代码。

二、功能处理方法是生产者
@RequestMapping(value = “/produces”, produces = “application/json”):表示将功能处理方法将生产json格式的数据,此时根据请求头中的Accept进行匹配,如请求头“Accept:application/json”时即可匹配;
@RequestMapping(value = “/produces”, produces = “application/xml”):表示将功能处理方法将生产xml格式的数据,此时根据请求头中的Accept进行匹配,如请求头“Accept:application/xml”时即可匹配。

此种方式相对使用@RequestMapping的“headers = “Accept=application/json””更能表明你的目的。

服务器控制器代码详解cn.javass.chapter6.web.controller.consumesproduces.ProducesController;
客户端代码类似于之前的Content-Type中的客户端,详见ProducesController.java代码。

当你有如下Accept头:
①Accept:text/html,application/xml,application/json
将按照如下顺序进行produces的匹配 ①text/html ②application/xml ③application/json
②Accept:application/xml;q=0.5,application/json;q=0.9,text/html
将按照如下顺序进行produces的匹配 ①text/html ②application/json ③application/xml
q参数为媒体类型的质量因子,越大则优先权越高(从0到1)
③Accept:/,text/*,text/html
将按照如下顺序进行produces的匹配 ①text/html ②text/* ③/

组合使用是“或”的关系

@RequestMapping(produces={“text/html”, “application/json”}) :将匹配“Accept:text/html”或“Accept:application/json”。

问题

消费的数据,如JSON数据、XML数据都是由我们读取请求的InputStream并根据需要自己转换为相应的模型数据,比较麻烦;
生产的数据,如JSON数据、XML数据都是由我们自己先把模型数据转换为json/xml等数据,然后输出响应流,也是比较麻烦的。

Spring提供了一组注解(@RequestBody、@ResponseBody)和一组转换类(HttpMessageConverter)来完成我们遇到的问题

0 0
原创粉丝点击