日期:2014-05-16  浏览次数:20652 次

关于spring mvc ajax请求乱码问题 StringHttpMessageConverter

昨天看了不少的帖子,都没有解决StringHttpMessageConverter问题,今天在http://stackoverflow.com上面看到个帖子,希望对大家有用。关于这个问题造成的原因我就不解释了,相信大家也看了超多的帖子了。

我用的版本是spring mvc3.1.3

?

我个人觉得这个帖子还比较实用。给大家分享下

http://stackoverflow.com/questions/3616359/who-sets-response-content-type-in-spring-mvc-responsebody/7772620#7772620

?

很多的帖子都是说重写StringHttpMessageConverter,我得强调下:

However, using this method you have to redefine all?HttpMessageConverters, and also it doesn't work with?<mvc:annotation-driven />.

然而,用这个方法你不得不重新定义HttpMessageConverters,并且 他不得和<mvc:annotation-driven />.这个标签一起工作。?

?

既然不能工作,我们怎么办呢?

这里有一篇文章,我也就大概看了下,具体里面有没有错,我也没仔细看,没去验证,大家可以借鉴下。

? http://www.mspring.org/post/2012/7/14/1344938579544.html

?

另外stackoverflow.com上面提供了令外一种最方便却丑陋的(非常规)的方法 ,拦截theAnnotationMethodHandlerAdapter?的实例化

?

public class EncodingPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String name)
            throws BeansException {
        if (bean instanceof AnnotationMethodHandlerAdapter) {
            HttpMessageConverter<?>[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters();
            for (HttpMessageConverter<?> conv: convs) {
                if (conv instanceof StringHttpMessageConverter) {
                    ((StringHttpMessageConverter) conv).setSupportedMediaTypes(
                        Arrays.asList(new MediaType("text", "html", 
                            Charset.forName("UTF-8"))));
                }
            }
        }
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String name)
            throws BeansException {
        return bean;
    }
}
-
<