spring mvc3.1 @ResponseBody注解生成大量Accept-Charset

Spring3 MVC使用@ResponseBody后会产生很大的响应头(Accept-Charset会达到4K+),原因在于默认情况下StringHttpMessageConverter.writeInternal()会将所有可用字符集回写到response响应头中:问题来了

解决方式:

一般我们都会重写springs mvc的HttpMessageConverter,改为utf-8编码:

package com.goldpalm.core.spring.mvc;

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.util.FileCopyUtils;

/**
 * 重写SpringMVC的字符串转换器,使用UTF-8编码
 * @since 2012-7-5 下午2:28:19
 * @author Jesse Lu
 */
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);
    }

    @SuppressWarnings("rawtypes")
    @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;
        }
    }

}

在xm中配置:注意红色圈起来的配置

<mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="com.goldpalm.core.spring.mvc.UTF8StringHttpMessageConverter">
				<property name="writeAcceptCharset" value="false" />
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
时间: 2024-08-06 18:53:45

spring mvc3.1 @ResponseBody注解生成大量Accept-Charset的相关文章

[转发]SPRING MVC3.2案例讲解--SPRING MVC3的@ResponseBody和ResponseEntity

在传统的开发过程中,我们的控制CONTROLL层通常需要转向一个JSP视图:但随着WEB2.0相关技术的崛起,我们很多时候只需要返回数据即可,而不是一个JSP页面. SPRING MVC3的@ResponseBody使Controller直接返回数据,而不是直接指向具体的视图:同时通过 MessageConverter和produces(如produces="text/plain;charset=UTF-8")可以返回各种格式的数据(XML,json,RSS,TEXT,字节流等),本章

spring 3.0 @ResponseBody注解返回中文问号乱码解决办法

前几天给公司做项目,很久没接触java项目的我,遇到了一个问题,就是我在利用异步到控制器中查询,然后返回jaon字符串到前台,字符串中包含中文,于是我直接用了@ResponseBody注解,来返回到前台. 但是中文一直是问号返回到前台.后来几经尝试,在配置文件中添加字符集还是没用,我发现我没写错,后来某次突然想到是不是因为放错位置了,果然,字符集配置应该放在包扫描配置之前,不然扫描完成后再去设置字符也没有意义了.所以以下配置为正确解决办法.. <bean class="org.spring

spring mvc3的注解@ResponseBody 自动返回jason

第三种利用spring mvc3的注解@ResponseBody 例如: [java] view plain copy print? @ResponseBody @RequestMapping("/list") public List<String> list(ModelMap modelMap) { String hql = "select c from Clothing c "; Page<Clothing> page = new Pag

spring mvc3.2.4生成的json配置

加入jackson包,在controller使用@ResponseBody注解,OK! 如果要全局支持jsonp(支持jsonp的做法:可以在controller的方法返回String类型,接收一下callback,然后 callback调用一下json结果就可以),可以再加一个StringHttpMessageConverter,不仅能解决中文乱码,还能把 json里面的换行\r\n去掉. <bean class="org.springframework.web.servlet.mvc.

Spring MVC @ResponseBody注解返回值中文乱码问题

在Spring MVC 的Controller中使用@ResponseBody注解向客户端返回数据时,如果没有特殊设置则中文将显示为乱码,此时需要在Spring-MVC.xml配置文件中加入如下代码 <!-- 避免IE在ajax请求时,返回json出现下载 --> <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHt

SpringMVC中使用@ResponseBody注解返回值,Ajax取得中文乱码解决方法

Spring使用AnnotationMethodHandlerAdapter的handleResponseBody方法, AnnotationMethodHandlerAdapter使用request header中"Accept"的值和messageConverter支持的MediaType进行匹配,然后会用"Accept"的第一个值写入 response的"Content-Type".一般的请求都是通过浏览器进行的,request heade

spring MVC3原理教程及其框架搭建实例

原文:spring MVC3原理教程及其框架搭建实例 http://www.zuidaima.com/share/1816340522191872.htm 一.前言: 大家好,Spring3 MVC是非常优秀的MVC框架,由其是在3.0版本发布后,现在有越来越多的团队选择了Spring3 MVC了.Spring3 MVC结构简单,应了那句话简单就是美,而且他强大不失灵活,性能也很优秀. 官方的下载网址是:http://www.springsource.org/download   (本文使用是的

SpringMVC源码剖析5:消息转换器HttpMessageConverter与@ResponseBody注解

转自 SpringMVC关于json.xml自动转换的原理研究[附带源码分析] 本系列文章首发于我的个人博客:https://h2pl.github.io/ 欢迎阅览我的CSDN专栏:Spring源码解析 https://blog.csdn.net/column/details/21851.html 部分代码会放在我的的Github:https://github.com/h2pl/ 目录 前言 现象 源码分析 实例讲解 关于配置 总结 参考资料 前言 SpringMVC是目前主流的Web MVC

@RequestBody, @ResponseBody 注解详解(转)

引言: 接上一篇文章讲述处理@RequestMapping的方法参数绑定之后,详细介绍下@RequestBody.@ResponseBody的具体用法和使用时机:同时对曾经看的一篇文章中讲述的某些部分进行澄清 (文章地址:http://www.byywee.com/page/M0/S702/702424.html). 简介: @RequestBody 作用: i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的