SpringMVC3的ResponseBody返回字符串(JSON)乱码问题解决
近日做一个小项目,用spring mvc 做到ajax请求获取jquery ztree 异步获取树返回json对象时出现了乱码,试了各种办法,查了各种资料,一开始以为是数据库的编码有问题,经测试没问题,又以为是jetty需要设置下响 应头,正在查找时突然想到可能是mvc的responseBody的问题,网上一查,果然是,用了一个设置最简单的办法,解决了问题,特将文章转贴于此, 与我一样遇到此问题的朋友们共享。
添加@RequestMapping注解,配置produces的值
@RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
SpringMVC3的ResponseBody返回字符串乱码问题解决
SpringMVC的@ResponseBody注解可以将请求方法返回的对象直接转换成JSON对象,但是当返回值是String的时候,中文会乱码, 原因是因为其中字符串转换和对象转换用的是两个转换器,而String的转换器中固定了转换编码为"ISO-8859-1",网上也很多种解决方法,有通 过配置Bean编码的,也有自己重写转换器的,我这里多次尝试未果,只能自己解决。
有两种解决办法:
1.返回字符串时,将字符串结果转换
return new String("你好".getBytes(), "ISO-8859-1");
2.添加@RequestMapping注解,配置produces的值
@RequestMapping(value = "/add", params = {"callback"}, produces = {"text/javascript;charset=UTF-8"})
以上提供的方法虽然需要额外配置,但相对灵活,喜欢一次性永久搞定的,还是应该考虑网上的方法,修改源码,或者替换默认的字符串转换器。
但是在使用<mvc:annotation-driven />配置的前提下,貌似网上的方法都不可靠,可能跟版本或者配置有关系
这边提供一种修改方法,我这边使用的是3.1的mvc
1.参考网上将默认的StringHttpMessageConverter重写一遍,将其中的编码改为UTF-8
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List; import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.util.FileCopyUtils; public class UTF8StringHttpMessageConverter extends AbstractHttpMessageConverter<String> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private final List<Charset> availableCharsets; private boolean writeAcceptCharset = true; public UTF8StringHttpMessageConverter() {
super(new MediaType("text", "plain", DEFAULT_CHARSET), MediaType.ALL);
this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());
} /**
* Indicates whether the {@code Accept-Charset} should be written to any outgoing request.
* <p>Default is {@code true}.
*/
public void setWriteAcceptCharset(boolean writeAcceptCharset) {
this.writeAcceptCharset = writeAcceptCharset;
} @Override
public boolean supports(Class<?> clazz) {
return String.class.equals(clazz);
} @Override
protected String readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException {
Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));
} @Override
protected Long getContentLength(String s, MediaType contentType) {
Charset charset = getContentTypeCharset(contentType);
try {
return (long) s.getBytes(charset.name()).length;
}
catch (UnsupportedEncodingException ex) {
// should not occur
throw new InternalError(ex.getMessage());
}
} @Override
protected void writeInternal(String s, HttpOutputMessage outputMessage) throws IOException {
if (writeAcceptCharset) {
outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
}
Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());
FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(), charset));
} /**
* Return the list of supported {@link Charset}.
*
* <p>By default, returns {@link Charset#availableCharsets()}. Can be overridden in subclasses.
*
* @return the list of accepted charsets
*/
protected List<Charset> getAcceptedCharsets() {
return this.availableCharsets;
} private Charset getContentTypeCharset(MediaType contentType) {
if (contentType != null && contentType.getCharSet() != null) {
return contentType.getCharSet();
}
else {
return DEFAULT_CHARSET;
}
} }
2.context配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <mvc:annotation-driven>
<mvc:message-converters>
<bean class="yourpackage.UTF8StringHttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven> ...... </beans>
SpringMVC3的ResponseBody返回字符串(JSON)乱码问题解决的更多相关文章
- SpringMVC 学习-返回字符串中文乱码问题解决
一.使用 SpringMVC 框架时,如果 HTTP 请求资源返回的是中文字符串,则会出现乱码.原因如下: SpringMVC 框架可以使用 @RequestBody 和 @ResponseBody ...
- SpringMvc Controller请求链接忽略大小写(包含拦截器)及@ResponseBody返回String中文乱码处理
SpringMvc Controller请求链接忽略大小写(包含拦截器)及@ResponseBody返回String中文乱码处理... @RequestMapping(value = "/t ...
- python3乱码问题:接口返回数据中文乱码问题解决
昨天测试接口出现有一个接口中文乱码问题,现象: 1 浏览器请求返回显示正常 2 用代码请求接口返回数据中文显示乱码 3 使用的python3,python3默认unicode编码,中文都是可以正常显示 ...
- ASP.NET 返回字符串 IE6乱码问题
项目A,所有的文件编码和内容编码都是UTF-8. 项目B,Index.aspx文件编码和页面内容编码都是GB2312. 项目A返回JSON格式数据给项目B时,其它浏览器都可以就是IE不行.后来在网上找 ...
- AD18 PCB中添加中文字符串显示乱码问题解决
该问题是由于字符串的自体类型设置问题,AD默认是[stroke],我们点击[TrueType]即可正常显示.PS:AD18搞啥呢,默认显示输入内容不行吗,找半天!!!
- spring 3 mvc 的 @ResponseBody返回数据中文乱码
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter&q ...
- Spring @ResponseBody 返回中文乱码问题
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt102 今天在使用spring 的时候,发现中文返回的是乱码. 经过研究发现, ...
- Spring MVC3返回JSON数据中文乱码问题解决(转)
Spring MVC3返回JSON数据中文乱码问题解决 查了下网上的一些资料,感觉比较复杂,这里,我这几使用两种很简单的办法解决了中文乱码问题. Spring版本:3.2.2.RELEASE Jack ...
- 解决Spring MVC @ResponseBody返回中文字符串乱码问题
spring mvc使用的默认处理字符串编码为ISO-8859-1 解决方法: 第一种方法: 对于需要返回字符串的方法添加注解,如下: @RequestMapping(value="/use ...
随机推荐
- error LNK2026: 模块对于 SAFESEH 映像是不安全的
解决方法: 1.打开该项目的“属性页”对话框. 2.单击“链接器”文件夹. 3.单击“命令行”属性页. 4.将 /SAFESEH:NO 键入“附加选项”框中,然后点击应用.
- Js文本溢出自动添加省略号ellipsis
原文: ellipsis: function(value, len, word) { //判断value有没有超过指定长度 if (value && v ...
- python--flask使用
Flask是一个使用 Python 编写的轻量级 Web 应用框架.下面我将使用Flask框架,创建一个简单的html页面示例. 1.项目的目录结构如下所示:exweb\ uniqueenv\ a ...
- CorelDRAW中拆清除调和效果的技巧
图形对象应用的调和效果达不到用户的满意,可以将该种调和效果清除,清除调和效果后,只保留起始对象和结束对象.CorelDRAW软件支持两种方法来清除调和对象,本教程将详解CorelDRAW中清除调和效果 ...
- dl,dt,dd,ul,li,ol区别
dl.dt.dd也是列表项,不过它们被忽视得比较厉害,人们只知道ul.ol.li,却经常漠视它们的存在,其实有时候,dl.dt.dd也是非常好用的,这两个家族是近亲,很多地方都是一模一样. dl类似u ...
- CodeFirstMigrations更新数据库结构(EF数据迁移)
背景 code first起初当修改model后,要持久化至数据库中时,总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges),此时就会产生一个问题,当我们的 ...
- C数据类型
结构体 因为数组中各元素的类型和长度都必须一致,以便于编译系统处理.为了解决这个问题,C语言中给出了另一种构造数据类型——“结构(structure)”或叫“结构体”.它相当于其它高级语言中的记录.“ ...
- DMALL刘江峰:生鲜市场具有巨大O2O改造空间
今日,全球移动互联网大会(GMIC)在北京-国家会议中心开幕.DMALL创始人刘江峰在全球O2O峰会论坛作主题发言时谈到,生鲜市场具有巨大O2O改造空间.同时这也是刘江峰在离开荣耀之后首次登台介绍自己 ...
- C# XML与Json之间相互转换实例详解
对于这转换其实很简单,其中最重要的就是先要引用类库.可以到官网进行下载引用http://json.codeplex.com. XML转换为Json字符串 string xml = @"< ...
- SQLSERVER 复制表--和复制有关的系统表
主数据库中的复制表 表名 说明 MSreplication_options 表存储供复制在内部使用的元数据. 此表存储在 master 数据库中. msdb 数据库中的复制表 表名 说明 MSagen ...