SpringMVC 乱码处理

SpringMVC @ResponseBody乱码处理:

原理:将StringHttpMessageConverter的默认编码设为UTF-8

 

方法1(推荐,参考自springside):

   配置spring-mvc.xml

<mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
    <!-- 将StringHttpMessageConverter的默认编码设为UTF-8 -->
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <constructor-arg value="UTF-8" />
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>

 

其他方法: 

 

方法2:

HttpServletResponse resp = (HttpServletResponse)response;
resp.setHeader("Cache-Control","no-cache");
resp.setContentType("application/json;charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
writer.write(json);

 

方法3:

@RequestMapping(value="/test",produces="text/plain;charset=UTF-8") 
@ResponseBody

 

 

方法4:

   重写BeanPostProcessor,并配置到spring-mvc.xml

public class BeanPostProcessorUtf8 implements BeanPostProcessor {

	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;
	}

	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

}
<bean id="beanPostProcessor" class="com.xxx.yyy.BeanPostProcessorUtf8" />

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(springMVC)