@RequestMapping的produces属性

设置Response的Content-Type


spring MVC中如何设置应答体的content type呢?


    @RequestMapping(value = "/json")
    @ResponseBody  
    public String upload(HttpServletRequest request, HttpServletResponse response,String contentType2)  
            throws IOException {  

        Demo1 demo1 = new Demo1()
        String json = JsonUtils.objectToJson(Demo1);//一个json工具类,转换为json

        return json;  

    }    

这样做,虽然在客户端确实相应的的事json,但是response的Content-type确实text/html。会有些问题发生,若是json中包含有中文,会乱码、

解决办法

    @RequestMapping(value="/pic/upload",produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8")

Producible Media Types的解释

You can narrow the primary mapping by specifying a list of producible media types. The request will be matched only if the Accept request header matches one of these values. Furthermore, use of the produces condition ensures the actual content type used to generate the response respects the media types specified in the producescondition. For example:

意思:你可以通过一个简化类型的列表来缩小主映射体,只有当Accept请求头与其中一个值匹配时,请求才会匹配。此外,使用生成条件确保所使用的实际内容类型

详情请查阅官方APIhttp://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/MediaType.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值