Url mass participation in the Chinese garbled get request

Often encounter Chinese pass parameters in the project, receiving the garbage problem in the background. So how should we be treated in such cases we reached the back of the received parameter is not garbage is what we want to receive, here are some of my knowledge and understanding.

A: get request with the Chinese url parameters, there are three ways to prevent the processed Chinese distortion

1、如果使用tomcat作为服务器,那么修改tomcat配置文件conf/server.xml中,在  <Connector port="8082" protocol="HTTP/1.1"  中加入  URIEncoding="utf-8"的编码集

2、前台需要对中文参数进行编码,调用js方法encodeURI(url),将url编码,然后请求。

              后台接受时,需处理String str = new String(request.getParameter("param").getBytes("iso8859-1"),"UTF-8");

             原因:tomcat不设置编码时,默认是iso8859-1,即tomcat默认会以iso8859-1编码接收get参数。 以上操作是将参数以iso8859-1编码转化为字节数组,然后再以UTF-8将字节数组转化为字符串。

              另外需注意在框架的使用中:request.setCharacterEncoding(encoding);只对post请求有效。而且,spring的CharacterEncodingFilter也只是做了request(和response).setCharacterEncoding(encoding);的操作。所以spring的filter配置不作用于get参数接收。

3、解决get请求,后台接受中文参数乱码处理的方法(搜索功能带参数)

       (1)前台获取数据,在js中进行编码处理

Here Insert Picture Description
encodeURI function takes utf-8 encode, and decode the server, the default is not uft-8 to decode, so there will be garbled.

Two encodeURI, is first encoded by UTF-8 form of URL, the second encoded by UTF-8 is still in the form of URL, but equivalent firstly a UTF-8 encoded in effect (in this case all have been converted to ASCII characters), and then an iso-8859-1 encoding, the same as the English characters for UTF-8 encoding effects and ISO- 8859-1 codes.

(2) Background decoding
Here Insert Picture Description
received parameters in the background when the first automatic request.getParameter first decodes () (may be gb2312, gbk, utf-8, iso-8859-1 character sets, etc., had no effect on the results) obtained ascii characters, then use UTF-8 decoding a second, usually java.net.URLDecoder ( "", "UTF- 8") method.

Decoding two encoded twice process:

UTF-8 encoding -> UTF-8 (iso-8859-1) encoding -> iso-8859-1 decoding -> UTF-8 decoding, encoding and decoding process is symmetrical, distortion does not occur.

Note:

1: Two encodeURI this way do not have to know the way of decoding server, you can also get the correct data.

2: get request parameters is recommended as far as possible without the Chinese, if recommended twice encodeURI encoded
Reprinted from: https: //www.cnblogs.com/tanzq/p/8748103.html

Released three original articles · won praise 0 · Views 210

Guess you like

Origin blog.csdn.net/qq_39433354/article/details/103923293