SpringMVC返回字符串/json数据到前台浏览器中文乱码问题
😂 这篇文章最后更新于1776天前,您需要注意相关的内容是否还可用。
目录导航
SpringMVC 直接返回字符串时,中文乱码出现问号(?)的问题,下列是各种解决方案:
- 通过配置spring-mvc.xml
- 在requestMapping中设置下编码
- response返回页面的话可直接设置编码
//-- 在annotation-driven中添加converter
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg ref="utf8Charset" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="utf8Charset" class="java.nio.charset.Charset" factory-method="forName">
<constructor-arg value="UTF-8" />
</bean>
或者
<mvc:annotation-driven >
<!-- 消息转换器 -->
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
或者
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>text/plain;charset=UTF-8</value>
<value>application/xml;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
或者
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="cn.dubby.what.util.MyStringHttpMessageConverter"/>
</mvc:annotation-driven>
在requestMapping中设置下编码
即在RequestMapping使用(produces = “text/html; charset=utf-8”)produces 作用根据请求头中的Accept进行匹配,如请求头“Accept:text/html”时即可匹配。
@RequestMapping(method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
json的话produces就是(根据自己需要修改):
produces = {"application/json;charset=UTF-8"}
response返回页面的话可直接设置编码
public static void write(HttpServletResponse response,Object o)throws Exception{
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println(o.toString());
out.flush();
out.close();
}
留言评论
暂无留言