SpringMVC 3のResponseBodyが文字列の文字化けしを返す問題解決


SpringMVCの@ResponseBody注記は、要求メソッドで返されたオブジェクトをJSONオブジェクトに直接変換できますが、戻り値がStringの場合、中国語は文字化けします
 
文字列変換とオブジェクト変換は2つの変換器を使用しているため、Stringの変換器には変換符号化が「ISO-8859-1」に固定されている
 
ネット上でも多くの解決方法があり、Bean符号化を構成することによって、自分でコンバータを書き換えることもあります.私はここで何度も試してみましたが、自分で解決するしかありません.
 
2つの解決策があります.
1.文字列を返すとき、文字列の結果を変換
 
return new String(" ".getBytes(), "ISO-8859-1");

 
2.@RequestMapping注記を追加し、producesの値を設定
 
@RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})

 
JSONPプロトコルを使用するためにcallbackとともに戻る必要があるので、定義は
 
@RequestMapping(value = "/add", params = {"callback"}, produces = {"text/javascript;charset=UTF-8"})

 
以上の方法では、追加の構成が必要ですが、比較的柔軟で、一度に永続的に行うのが好きです.やはり、ネット上の方法を考慮したり、ソースコードを変更したり、デフォルトの文字列変換器を置き換えたりする必要があります.
しかし構成を使用する前提では、ネット上の方法は信頼できないようで、バージョンや構成と関係がある可能性があります.
 
こちらは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>