SpringMVC 转换ajax的json数据乱码问题

Springmvc用ajax传输json数据http://blog.csdn.net/u012457196/article/details/43498139

在springmvc3中,已经集成了Jackson(json处理器)来处理数据输出json格式,spring中封装的类是org.springframework.http.converter.json.MappingJackson2HttpMessageConverter这个json转换器,如果是springmvc3.2之前的版本,可以使用org.springframework.http.converter.MappingJacksonHttpMessageConverter这个json转换器。

springmvc使用@ResponseBody返回json乱码解决方法http://www.itxxz.com/a/javashili/ask/2014/1222/501.html

1.springmvc3.2以上的版本解决乱码的方法:

  第一步:在配置中加入:

<mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8" />
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                     <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                         <property name="failOnEmptyBeans" value="false" />
                     </bean>
                 </property>
            </bean>
        </mvc:message-converters>
     </mvc:annotation-driven>

或者可以这样写

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="jsonRequestConverter" />
			</list>
		</property>
	</bean>
	<bean id="jsonRequestConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>

 第二步:需要的加入的jacksonjar如下:

<dependency>

        <groupId>com.fasterxml.jackson.core</groupId>

        <artifactId>jackson-annotations</artifactId>

        <version>2.1.0</version>

      </dependency>

      <dependency>

        <groupId>com.fasterxml.jackson.core</groupId>

        <artifactId>jackson-core</artifactId>

        <version>2.1.0</version>

      </dependency>

      <dependency>

        <groupId>com.fasterxml.jackson.core</groupId>

        <artifactId>jackson-databind</artifactId>

        <version>2.1.0</version>

      </dependency>

      <dependency>

        <groupId>com.fasterxml.jackson.module</groupId>

        <artifactId>jackson-module-jaxb-annotations</artifactId>

        <version>2.1.0</version>

      </dependency>
  

另一种方法:,貌似偶尔出问题,还没找原因

package cn.com.voge.utils;

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.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
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;

	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;
		}
	}
}
<mvc:annotation-driven>   
	    <mvc:message-converters register-defaults="true">   
	        <bean class="cn.com.voge.utils.UTF8StringHttpMessageConverter"/>   
	    </mvc:message-converters>   
	</mvc:annotation-driven>

2.springmvc3.1解决中文乱码的方法:

  第一步:在配置文件中加入以下代码:

<mvc:annotation-driven>
 
    <mvc:message-converters register-defaults="true">
 
      <bean class="com.util.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; 
          } 
      } 
  }

 第三步:加入需要的jackson包:

<dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.8.8</version>
      </dependency>
      <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.8.8</version>
      </dependency>

相关推荐