Spring Mvc中@ResponseBody中文乱码解决汇总

 spring 3 mvc 的 @ResponseBody返回数据用起来很方便,但是中文乱码,而且返回的Content-Type不带编码信息,网上有很多解决方法,但是大部分都存在一些问题,这里只介绍一种,如下:
自己写一个继承StringHttpMessageConverter的类UTF8StringHttpMessageConverter,内容参考 StringHttpMessageConverter.java中的代码, 该类参考代码如下:
package com.aikang.common;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.FileCopyUtils;

public class UTF8StringHttpMessageConverter extends StringHttpMessageConverter {
	private static final MediaType utf8 = new MediaType("text", "plain",
			Charset.forName("UTF-8"));
	private boolean writeAcceptCharset = true;

	@Override
	protected MediaType getDefaultContentType(String t) {
		return utf8;
	}

	@Override
	protected List getAcceptedCharsets() {
		return Arrays.asList(utf8.getCharSet());
	}

	@Override
	protected void writeInternal(String s, HttpOutputMessage outputMessage)
			throws IOException {
		if (this.writeAcceptCharset) {
			outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
		}
		Charset charset = utf8.getCharSet();
		FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(),
				charset));
	}

	public boolean isWriteAcceptCharset() {
		return writeAcceptCharset;
	}

	public void setWriteAcceptCharset(boolean writeAcceptCharset) {
		this.writeAcceptCharset = writeAcceptCharset;
	}
}

spring-servlet的配置文件如下:


		
			
				
			
		
	

注:一定要放在扫描器之前

参考:

http://blog.csdn.net/wuxinzaiyu/article/details/8813974


http://wenku.baidu.com/link?url=I1OjprSVraCMRmg9JZi5RyX2DTn2kPTdkufuNliBkYB7juWOtVCKvKvm1EV4mb0imSQ_YXWxVVLNZW7UiNHStoNlHCILDqebRmRbJ4dd-T7




你可能感兴趣的:(问题处理)