@Responsebody utf8 Chinese gibberish

来源:互联网 发布:linux shell sleep 编辑:程序博客网 时间:2024/06/05 13:28

Chinese gibberish–>controller return a String “中文” to html, but html shows “??”.

create a class like

package com.fc.test.utils;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.BeanPostProcessor;import org.springframework.http.MediaType;import org.springframework.http.converter.StringHttpMessageConverter;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.List;/** * Created by  */public class UTF8StringBeanPostProcessor implements BeanPostProcessor {    @Override    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {        if (o instanceof StringHttpMessageConverter){            MediaType mediaType = new MediaType("text", "plain", Charset.forName("UTF-8"));            List<MediaType> types = new ArrayList<MediaType>();            types.add(mediaType);            ((StringHttpMessageConverter) o).setSupportedMediaTypes(types);        }        return o;    }    @Override    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {        return o;    }}

and add it a bean in spring-mvc.xml

<bean class="com.fc.test.utils.UTF8StringBeanPostProcessor"/>
原创粉丝点击