前后端交互,乱码根本原因分析

encodeURI()函数  返回URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。

http://www.w3school.com.cn/jsref/jsref_encodeuri.asp

encodeURIComponent(URIstring)  返回URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。

http://www.w3school.com.cn/jsref/jsref_encodeURIComponent.asp

decodeURIComponent(URIstring)  返回URIstring 的副本,其中的十六进制转义序列将被它们表示的字符替换。

http://www.w3school.com.cn/jsref/jsref_decodeURIComponent.asp

decodeURI(URIstring) 返回URIstring 的副本,其中的十六进制转义序列将被它们表示的字符替换。

http://www.w3school.com.cn/jsref/jsref_decodeURI.asp

encodeUri和encodeURLComponent的区别:

不支持编码的字符不一样,使用场景不同

encodeURI主要用于直接赋值给地址栏时候,而encodeURIComponent主要用于url的query参数:

http://www.cnblogs.com/huangjacky/p/4015690.html

urlEncodeDemo



 

-------------------

前后台交互:

前端 --- HTTP ----> TOMCAT ----> MVC controller(参数注入) ----> 业务处理

前端:

1 window.location.href=XXX   XXX如果含有中文字符会被浏览器自动encode

http://sear.qbao.com/static/web/search.html?type=2&keyWord=%E5%93%88%E5%93%88   哈哈

http://sear.qbao.com/static/web/search.html?type=2&keyWord=ss

window.location.href=XX_URL,相当于把XX_URL复制到地址栏然后回车

       window.location.href 并不是说遇到特殊字符就会encode,比如说%是特殊字符,但是它不会被encode

       

  2 ajax 提交参照http://curious.iteye.com/admin/blogs/2298465

});

---------------------------------------------

后端:(tomcat+Spring MVC)

TOMCAT:

在Tomcat5.0之后,tomcat会使用默认的编码方式decodeURL,request.setCharacterEncoding设置的编码方式默认不生效(URL中可能含有键值对 by 表单get提交,ajax-get提交,windows.location.href,jsonp调用)

要解决该问题,可以在Tomcat的配置文件的Connector标签中设置 useBodyEncodingForURI或者URIEncoding属性,

其中useBodyEncodingForURI参数表示:是否用request.setCharacterEncoding的参数对URI进行decode,在默认情况下,该参数为false

URIEncoding表示:是否用指定的编码方式对URL进行解码

tomcat-docs/config/http.html文档的说明

URIEncoding:This specifies the character encoding used to decode the URI bytes,

after %xx decoding the URL. If not specified, ISO-8859-1 will be used. 

useBodyEncodingForURI:This specifies if the encoding specified in contentType should be used for URI query parameters,instead of using the URIEncoding.

--------------

Spring MVC 

仅仅是参数值的自动注入,注入参数值,是通过request.getparameter得到的,需要考虑乱码问题

一个重要的配置,设置编码方式

	<filter>
		<filter-name>SetCharacterEncoding</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>
	</filter>
	

	<filter-mapping>
		<filter-name>SetCharacterEncoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

=============

乱码根本原因:

前后台的编码方式不一致

乱码的常见情况:

后台处理前端传递的get请求参数出现乱码,原因就在于tomcat的urlDecode在不做特殊配置的场景下,用的是默认的ISO-8859-1 进行解码,而前端传递过来的特殊字符通常是UrlEncode-UTF8encode过的

======================

如何解决乱码

1  优先使用post提交

2  二次encode

<html>
	<script>
			window.location.href="http://s.qbao.com/search.html?type=2&keyWord="+encodeURIComponent(encodeURIComponent('哈哈'));
	</script>	
</html>

 

猜你喜欢

转载自curious.iteye.com/blog/2290779