HttpMessageConverter
HTTP 請(qǐng)求和響應(yīng)是基于文本的幔翰,意味著瀏覽器和服務(wù)器通過交換原始文本進(jìn)行通信漩氨。但是,使用 Spring遗增,controller 類中的方法返回純 ‘String’ 類型和域模型(或其他 Java 內(nèi)建對(duì)象)叫惊。如何將對(duì)象序列化/反序列化為原始文本?這由HttpMessageConverter 處理做修。
- Http請(qǐng)求和響應(yīng)報(bào)文本質(zhì)上都是一串字符串
- 請(qǐng)求報(bào)文轉(zhuǎn)換成 ServletInputStream的輸入流
- 響應(yīng)報(bào)文轉(zhuǎn)換成ServletOutputStream的輸出流
@RequestBody
作用:
1. 該注解用于讀取Request請(qǐng)求的body部分?jǐn)?shù)據(jù)霍狰,使用系統(tǒng)默認(rèn)配置的HttpMessageConverter進(jìn)行解析,然后把相應(yīng)的數(shù)據(jù)綁定到要返回的對(duì)象上缓待;
2. 再把HttpMessageConverter返回的對(duì)象數(shù)據(jù)綁定到 controller中方法的參數(shù)上蚓耽。
@ResponseBody
作用:
該注解用于將Controller的方法返回的對(duì)象,通過適當(dāng)?shù)腍ttpMessageConverter轉(zhuǎn)換為指定格式后旋炒,寫入到Response對(duì)象的body數(shù)據(jù)區(qū)步悠。可以返回其他格式(json/xml等)
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>