SpringMVC的@ResponseBody亂碼

SpringMVC的@ResponseBody註解可以將請求方法返回的對象直接轉換成JSON對象,但是當返回值是String的時候,中文會亂碼。

 原因是因爲其中字符串轉換和對象轉換用的是兩個轉換器,而String的轉換器中固定了轉換編碼爲"ISO-8859-1" 


在網上查詢了一下解決辦法:


解決辦法:


1.返回字符串時,將字符串結果轉

return new String("你好".getBytes(), "ISO-8859-1");  //注意這種返回到前端的編碼是ISO-8859-1,對於需要utf-8的不行。


2.添加@RequestMapping註解,配置produces的值


@RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})


3.StringHttpMessageConverter重寫

public class UTF8StringHttpMessageConverter extends
        AbstractHttpMessageConverter<String> {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private final List<Charset> availableCharsets;

    private boolean writeAcceptCharset = true;

    public UTF8StringHttpMessageConverter() {
        super(new MediaType("text", "plain", DEFAULT_CHARSET), MediaType.ALL);
        this.availableCharsets = new ArrayList<Charset>(Charset
                .availableCharsets().values());
    }

    /**
     * Indicates whether the {@code Accept-Charset} should be written to any
     * outgoing request.
     * <p>
     * Default is {@code true}.
     */
    public void setWriteAcceptCharset(boolean writeAcceptCharset) {
        this.writeAcceptCharset = writeAcceptCharset;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return String.class.equals(clazz);
    }

    @Override
    protected String readInternal(Class clazz, HttpInputMessage inputMessage)
            throws IOException {
        Charset charset = getContentTypeCharset(inputMessage.getHeaders()
                .getContentType());
        return FileCopyUtils.copyToString(new InputStreamReader(inputMessage
                .getBody(), charset));
    }

    @Override
    protected Long getContentLength(String s, MediaType contentType) {
        Charset charset = getContentTypeCharset(contentType);
        try {
            return (long) s.getBytes(charset.name()).length;
        } catch (UnsupportedEncodingException ex) {
            // should not occur
            throw new InternalError(ex.getMessage());
        }
    }

    @Override
    protected void writeInternal(String s, HttpOutputMessage outputMessage)
            throws IOException {
        if (writeAcceptCharset) {
            outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
        }
        Charset charset = getContentTypeCharset(outputMessage.getHeaders()
                .getContentType());
        FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(),
                charset));
    }

    /**
     * Return the list of supported {@link Charset}.
     * 
     * <p>
     * By default, returns {@link Charset#availableCharsets()}. Can be
     * overridden in subclasses.
     * 
     * @return the list of accepted charsets
     */
    protected List<Charset> getAcceptedCharsets() {
        return this.availableCharsets;
    }

    private Charset getContentTypeCharset(MediaType contentType) {
        if (contentType != null && contentType.getCharSet() != null) {
            return contentType.getCharSet();
        } else {
            return DEFAULT_CHARSET;
        }
    }

}


配置文件:

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="xx.xx.xx.UTF8StringHttpMessageConverter" />
        </mvc:message-converters>
    </mvc:annotation-driven>


重點:成功的解決辦法

最後,我自己親自測試了,自用將<mvc:annotation-driven />放在

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">之後即可,也沒有重寫StringHttpMessageConverter


附上我的配置:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringHttpMessageConverter" />
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<!-- 默認的註解映射的支持,注意這個必須放在RequestMappingHandlerAdapter之後 -->
<mvc:annotation-driven />
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>


<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章