0
点赞
收藏
分享

微信扫一扫

SpringMVC(28):json数据的中文乱码-解决与示例

编程练习生J 2022-07-27 阅读 81


2018年2月14日

【0】@ResponseBody把数据向前台页面以JSON格式进行数据传递的时候,若返回的值是中文字符串,则会出现乱码。

原因:消息转换器固定了转换字符编码--“ISO-8859-1”。

解决方案有两种:(1)控制器处理方法的@RequestMapping注解配置produces;(2)装配消息转换器StringHttpMessageConverter;


【1】Controller层:

produces:指定返回的内容类型,produces = {"application/json;chartset=UTF-8"}:表示该处理方法将产生JSON格式的数据,此时会根据请求报文头中的Accep进行匹配,若请求报文头“Accept:application/json”时即可匹配,并且字符串的转换编码为"UTF-8"。更改为如下:


@RequestMapping(value="/view.html",method=RequestMethod.GET,produces = {"application/json;chartset=UTF-8"})
@ResponseBody
public Object userView(@RequestParam String id){
System.out.println("UserController-userView");
****省略
}


【2】

装配消息转换器 StringHttpMessageConverter

修改配置文件springmvc-servlet.xml,关键配置代码如下:

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


解释:

(1)上述配置,通过配置 StringHttpMessageConverter 的 supportedMediaTypes 属性指定媒体类型为 application/json ,字符编码为UTF-8。

(2)在springmvc 配置了消息转换器后,就可以去掉@RequestMapping注解配置的produces了。




举报

相关推荐

0 条评论