@RequestMapping的produces属性

来源:互联网 发布:java中文gbk编码转换 编辑:程序博客网 时间:2024/05/18 17:54

设置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

原创粉丝点击