Today, I am working on a project to redirect the request parameters to the page.
Chinese parameters are garbled, so I checked the relevant information online:
Http://hpfgc.blog.163.com/blog/static/147995572009111462947544/
Http://blog.sina.com.cn/s/blog_632bb1950100l77z.html
The HTTP request is URL-encoded by the ISO-8859-1. If the Content-Type of the page is UTF-8, the request will be transferred after being converted to UTF-8.
In this way, after receiving the byte stream, the server converts it into a corresponding character, request. getparameter ("XX") directly obtains the string, and the conversion system from byte to the bytes stream helps us (error source)
Solution:
1. No Encoded URL
HTML page:
VaR url = "./suggestservlet? Tagname = "+ document. getelementbyid ('tagname'). value;
The parameter is in Chinese and is passed to the container. The Container determines the encoding used for parsing.
When using the Java method to obtain parameters
String myparam = request. getparameter ("tagname"); // The returned result is a garbled string request. getcharacterencoding (); // The returned result is a null value.
The default Tomcat is ISO-8859-1 encoding parsing, which is why we get garbled.
Myparam = new string (myparam. getbytes ("ISO-8859-1"), "UTF-8"); this way to get the Chinese, the following according to the charset statement to this, if it is GBK, it is changed to the corresponding can be.
2. Use JavaScript encodeuri to encode Chinese Parameters
HTML page:
VaR url = "./suggestservlet? Tagname = "+ encodeuri (document. getelementbyid ('tagname'). value );
The parameter is encoded.
Get this parameter after Servlet
String myparam = request. getparameter ("tagname"); // The string encoded by the UTF-8 is not garbled
To obtain Chinese characters, we need to convert the encoding again.
String decodingparam = urldecoder. Decode (myparam, "UTF-8 ");
Before making a URL request, use JavaScript encodeuri (URL)
Import the corresponding classes in Java:
Java.net. urldecoder
Java.net. urlencoder
In addition !!
In the background JavaProgramThe value is decoded once, but the decoding result is still incorrect. Therefore, we can perform two encoding operations on the page, so that the background will be automatically offset once, and then use xx = java.net. urldecoder. decode (XX, "UTF-8");/* handle exceptions */perform a decoding.
VaR url = "./suggestservlet? Tagname = "+ encodeuri (document. getelementbyid ('tagname'). Value ));