有人跟踪@ResponseBody
下面提供2中解决方法:
方法一
我遇到这个问题的时候,查阅了一下资料,采用了一个比较简单的方法来解决这个问题,就是需要服务器返回中文的时候不使用这个注解,而是直接用HttpServletResponse的对象来完成传输,在服务器端可以通过response.setContentType("text/plain;charset=UTF-8");来设定编码类型,这样就不会出现中文乱码了。
服务器端核心代码如下:
@RequestMapping(value = "test", method = RequestMethod.POST)
public void test(HttpServletRequest request,
HttpServletResponse response) {
String result = null;
//取得客户端传来的值
String userName = request.getParameter("userName");
//向客户端返回一句话
result = "您好!";
PrintWriter out = null;
response.setContentType("text/plain;charset=UTF-8");
try {
out = response.getWriter();
out.write(result.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
out.close();
}
}
返回值时根据自己的数据类型进行设置,常用的有:
response.setContentType("text/html; charset=utf-8"); html
response.setContentType("text/plain; charset=utf-8"); 文本
response.setContentType("application/json; charset=utf-8"); 数据
response.setContentType("application/xml; charset=utf-8");
方法二
2014-07-11
今天再次查找了一下这个问题,有了一个更好的解决方法,使用spring的BeanPostProcessor接口实现,在自己的工程中新建一个类,如下:
package springmvc.extention;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
/**
* 解决spring MVC3 中@ResponseBody的中文乱码问题
*/
public class UTF8StringBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof StringHttpMessageConverter) {
MediaType mediaType = new MediaType("text", "plain", Charset.forName("UTF-8"));
List<MediaType> types = new ArrayList<MediaType>();
types.add(mediaType);
((StringHttpMessageConverter) bean).setSupportedMediaTypes(types);
}
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
然后在自己的Spring配置文件中注册这个bean就可以了,再试试自己的程序,发现问题解决了。
<!-- 解决使用@ResponseBody 的中文乱码。 -->
<bean class="springmvc.extention.UTF8StringBeanPostProcessor"></bean>
(原文地址:http://blog.csdn.net/zhshulin)