[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[备忘]SpringMvc的输出Content-Type

上一篇:[备忘]java航班号匹配正则
下一篇:[备忘]linux下,脚本批量删除redis里的N多Key

添加日期:2017/10/25 10:48:30 快速返回   返回列表 阅读2334次


@RequestMapping(value = { "/api/v1/test" }, method = { RequestMethod.POST }, produces="application/json;charset=UTF-8")
@ResponseBody
public String cancelCall(HttpServletResponse rsp) {
   rsp.addHeader("Access-Control-Allow-Origin", "*");
   return "{\"url\":\"http://192.168.1.1/notify\"}";
}



(1)接收数据
根据Request对象header部分的Content-Type类型,逐一匹配合适的HttpMessageConverter来读取数据

(2)输出数据(使用@ResponseBody时)
根据Request对象header部分的Accept属性(逗号分隔),逐一按accept中的类型,去遍历找到能处理的HttpMessageConverter

(3)如果自己完全控制,就直接
resp.setContentType(type);
resp.getWriter().write("..");
即可,
方法返回类型写void,不需要@ResponseBody注解。

(4)用了@ResponseBody,就表示由springMvc来控制如何转换。
    <1>输出的Content-Type
    <2>输出的内容,比如一个Bean转json。

在@RequestMapping指定produces,就指定了输出使用的Content-Type。否则会根据请求的Accept属性挨个去试。

另外,请求的Accept中应该兼容指定的produces,
如果请求的Accept是text/plain,而方法的produces是application/json,那么请求会报错。
如果请求的Accept是*,或者包含application/*,或者包含application/json,那么都是可以的

-----------------------------------------------------------------


    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
        <property name="messageConverters">  
            <list>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg>
                        <value>UTF-8</value>
                    </constructor-arg>
                </bean>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
                    <property name="supportedMediaTypes">  
                        <list>  
                            <value>text/html;charset=UTF-8</value>  
                        </list>  
                    </property>  
                </bean>  
            </list>  
        </property>  
    </bean>


 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved