首页 > 其他分享 >SpringMVC3的ResponseBody返回字符串乱码问题解决

SpringMVC3的ResponseBody返回字符串乱码问题解决

时间:2023-08-28 10:37:09浏览次数:45  
标签:charset return String java Charset 乱码 ResponseBody import SpringMVC3


SpringMVC的@ResponseBody注解可以将请求方法返回的对象直接转换成JSON对象,但是当返回值是String的时候,中文会乱码

 

原因是因为其中字符串转换和对象转换用的是两个转换器,而String的转换器中固定了转换编码为"ISO-8859-1"

 

网上也很多种解决方法,有通过配置Bean编码的,也有自己重写转换器的,我这里多次尝试未果,只能自己解决。

 

有两种解决办法:

1.返回字符串时,将字符串结果转换

 

return new String("你好".getBytes(), "ISO-8859-1");

 

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

 

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

 

由于我是为了使用JSONP协议,需要连同callback一起返回,所以我定义的是

 

@RequestMapping(value = "/add", params = {"callback"}, produces = {"text/javascript;charset=UTF-8"})

 

以上提供的方法虽然需要额外配置,但相对灵活,喜欢一次性永久搞定的,还是应该考虑网上的方法,修改源码,或者替换默认的字符串转换器。

但是在使用<mvc:annotation-driven />配置的前提下,貌似网上的方法都不可靠,可能跟版本或者配置有关系

 

这边提供一种修改方法,我这边使用的是3.1的mvc

1.参考网上将默认的StringHttpMessageConverter重写一遍,将其中的编码改为UTF-8

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;

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

}

 

2.context配置


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
                                                		  http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                                                		  http://www.springframework.org/schema/context 
                                                		  http://www.springframework.org/schema/context/spring-context-3.1.xsd
                                                		  http://www.springframework.org/schema/aop 
                                                		  http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
                                                		  http://www.springframework.org/schema/tx 
                                                		  http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                                                		  http://www.springframework.org/schema/mvc 
                                                		  http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                                                		  http://www.springframework.org/schema/context 
                                                		  http://www.springframework.org/schema/context/spring-context-3.1.xsd">


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

......
	
</beans>

 

 

标签:charset,return,String,java,Charset,乱码,ResponseBody,import,SpringMVC3
From: https://blog.51cto.com/u_16237557/7260819

相关文章

  • Redis中文乱码解决方案
    问题描述刚开始学Redis,当我存入中文并想要读取时发现控制台上显示的是乱码......
  • Oracle-TiDB迁移-生僻字乱码问题
    作者:longzhuquan背景某去O场景业务上线测试,再执行某张表缩字段时报错。现象执行缩字段语句ALTERTABLEschemaname.tablenameMODIFYCOLUMNlicensenovarchar(50)CHARACTERSETutf8mb4COLLATEutf8mb4_binNULLCOMMENT'发动机号';报错信息"incorrectstringvalu......
  • java字符串乱码判断
    publicstaticbooleanerrCodes(Stringstr){return!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(str));}//扩展判断是否为中文publicstaticbooleancheckChinese(charch){returnString.valueOf(ch).match......
  • SpringMVC 中中文乱码解决
    请求中文乱码在web.xml中配置spring自带的过滤器org.springframework.web.filter.CharacterEncodingFilter,只可以解决请求<!--spring自带的解决中文乱码的filter--><filter><filter-name>encoding</filter-name><filter-class>org.springframework.web.fil......
  • Java Web中出现的一些乱码问题总结(详解)
    三、JavaWeb中出现的一些乱码问题总结(详解) 一、response.getWriter().write()和response.getWriter().print()的区别response.getWriter()返回的是PrintWriter,这是一个打印输出流response.getWriter().write()和response.getWriter().print()是响应给客户端的东西,如果不用......
  • ElementUI图标icon乱码问题
    如题:ELementUI图标icon乱码问题原因:在build编译时编译器处理导致的解决方案方案一:将saas更换为node-saas,安装不了问题可查看这里方案二:升级saas和sass-loader方案三:将element引入的样式代码注释,然后再main.js添加一行引入样式代码注释代码:import'~element-ui/packages/t......
  • 解决pytest html报告中文乱码的问题
    pytest-html指定版本3.1.1即可解决pipinstallpytest-html==3.1.1    ......
  • Web_PHP_MySQL_XAMPP下MYSQL中文乱码问题的解决
    1、找到xampp安装目录下的D:\xampp\mysql\bin\my.ini文件并打开; 2、找到标记[mysqld]和标记[mysql]两处; 3、在这2处标记下分别添加编码配置信息:default-character-set=gbk;修改后如下:->Ini代码 [mysql] no-auto-rehash default-character-set=gbk  [mysql......
  • Web_PHP_PHPsubstr截取中文字符出现乱码解决;
          PHPsubstr截取中文字符时通常会出现乱码,我们可以通过使用mbstring扩展库的mb_substr截取;自己书写截取函数等方式来解决这一问题。      substr()函数可以分割文字,但要分割的文字如果包括中文字符往往会遇到问题,这时可以用mb_substr()/mb_strcut这个函数,mb_sub......
  • idea 控制台日志乱码
    Help-->EditCustom-->VM-->Options,打开idea.vmoptions,文件位置:JetBrains\jetbra\vmoptions  在文件末尾添加:-Dfile.encoding=UTF-8 ......