Spring返回json时中文显示乱码的问题,网络上大多数的方法在Spring 3.1下都失效了。搞不懂Spring怎么不修正这个问题呢?
多费周折最终还是找到解决方案,并亲测通过,故分享之。
简单的说就是新建个转换类再注入。就那么简单,这就是开源的好处啊!
配置:
- <mvc:annotation-driven>
- <mvc:message-converters register-defaults="true">
- <bean class="com.abc.spring.UTF8StringHttpMessageConverter"/>
- </mvc:message-converters>
- </mvc:annotation-driven>
- public class UTF8StringHttpMessageConverter extends
- AbstractHttpMessageConverter<String> {
- public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
- private final List<Charset> availableCharsets;
- public UTF8StringHttpMessageConverter() {
- this(DEFAULT_CHARSET);
- }
- public UTF8StringHttpMessageConverter(Charset defaultCharset) {
- super(new MediaType("text", "plain", defaultCharset), MediaType.ALL);
- this.availableCharsets = new ArrayList<Charset>(Charset
- .availableCharsets().values());
- }
- @Override
- protected boolean supports(Class<?> clazz) {
- return String.class.equals(clazz);
- }
- @Override
- protected String readInternal(Class<? extends String> clazz,
- HttpInputMessage inputMessage) throws IOException,
- HttpMessageNotReadableException {
- MediaType contentType = inputMessage.getHeaders().getContentType();
- Charset charset = contentType.getCharSet() != null ? contentType
- .getCharSet() : DEFAULT_CHARSET;
- return FileCopyUtils.copyToString(new InputStreamReader(inputMessage
- .getBody(), charset));
- }
- @Override
- protected void writeInternal(String t, HttpOutputMessage outputMessage)
- throws IOException, HttpMessageNotWritableException {
- MediaType contentType = outputMessage.getHeaders().getContentType();
- Charset charset = contentType.getCharSet() != null ? contentType
- .getCharSet() : DEFAULT_CHARSET;
- FileCopyUtils.copy(t, new OutputStreamWriter(outputMessage.getBody(),
- charset));
- }
- protected List<Charset> getAcceptedCharsets() {
- return this.availableCharsets;
- }
- @Override
- protected Long getContentLength(String s, MediaType contentType) {
- if (contentType != null && contentType.getCharSet() != null) {
- Charset charset = contentType.getCharSet();
- try {
- return (long) s.getBytes(charset.name()).length;
- } catch (UnsupportedEncodingException ex) {
- throw new InternalError(ex.getMessage());
- }
- } else {
- return null;
- }
- }
- }