代码改变世界

17_10_10 乱码问题总结

2017-10-10 17:50  小歪1991  阅读(201)  评论(0编辑  收藏  举报

乱码类型:

1.post请求:jsp->Controller 传入参数时

2.ajax异步请求:Controller->jsp 取出数据时

UTF-8编码:8-bit Unicode Transformation Format;它对英文使用8位(即一个字节),中文使用24位(三个字节)来编码。对于英文字符较多的论坛则用UTF-8节省空间;

GBK编码:(Guo-Biao Kuozhan) Chinese Internal Code Specification;  UTF8是国际编码,它的通用性比较好,外国人也可以浏览论坛;GBK是国家编码,通用性比UTF8差,不过UTF8占用的数据库比GBK大

乱码检测处理

1.post请求:(常在form表单内部)

方法一:在web.xml中配置filter即可->对所有post表单均有效

<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:mybatis-spring.xml</param-value>
	</context-param>

	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

方法二:如果form表单较少:

此时处理1.:加入enctype;虽然没有上传文件,但依然有效
<form  action="uploadfile" method="post" enctype="multipart/form-data" >	

此时处理2:在controller层拿到jsp传的数据,直接强转
String param= new String(request.getParameter("param").getBytes("ISO-8859-1"), "UTF-8");
方法三:
参考babasport第二天05::26分钟;修改tomcat配置文件:confg

2.ajax异步请求:加入produces = "text/html;charset=UTF-8


@RequestMapping(value = "/ajaxContent", produces = "text/html;charset=UTF-8;")