在服务器返回中文的时候不使用这个注解,而是直接用HttpServletResponse的对象来完成传输,在服务器端可以通过response.setContentType(“text/plain;charset=UTF-8”);来设定编码类型,这样就不会出现中文乱码了
返回值时根据自己的数据类型进行设置,常用的有:
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"); xml
方法二 可以新建一个实现了BeanPostProcessor 的类
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>