控制台日志提示 Written [返回消息] as "text/plain" using [org.springframework.http.converter.StringHttpMessageConverter@48088cc9]
我spring-mvc配置文件里配置如下:
<mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
中文依旧乱码,我发生的原因是这里 只设置了 application/json 数据格式为 UTF-8, 使用 @ResponseBody 在我使用的spring版本中(4.3.20),它返回字符串的响应头为 "text/plain", 而不管什么响应头 默认编码都是 ISO-8859-1 ,也就是我需要为 text/plain 响应头配置编码:
<mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> <value>text/plain;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
那么问题来了,我应该在哪里配置 @ResponseBody 默认的响应头为什么类型的,目前没找到,如果不是通过配置文件就方便了, 在 @RequestMapping 注解设置如下:
@RequestMapping(value = "/add",produces="text/html;charset=UTF-8")
这样既可以设置响应头类型,也可以设置该响应头编码
缺点: 每个请求映射都需要配置,一般对于特殊需求这样做,很多项目中我们整体采用的都是同种格式,所以不如在配置文件中去全局设置