Java get encoding/decoding
Encoding/Decoding of parameters when accessing URLs in GET mode: Encoding/transmission/decoding
Basic process:
Public static void main (String args []) {
String tsptString = "Chinese ";
// 1. Encoding (the browser will encode the webpage according to the webpage encoding method)
String tempString = URLEncoder. encode (tsptString, "GBK ");
// 2. Transmission
System. out. println (tempString );
// 3. Decoding (automatically decoded by the Tomcat container according to the default encoding method)
String resultString = URLDecoder. decode (tempString, "ISO-8859-1 ");
// View
System. out. println (resultString );
}
The above method causes garbled characters due to inconsistent codec methods. You can use the following method to unify the encoding method:
1. Specify the webpage encoding on the client
A) specify the GBK mode on the page: submit. in the jsp tutorial, <% @ page pageEncoding = "GBK" %>, Response in Servelet. setContentType ("text/html; charset = GBK ");
B) specify the GBK mode in the browser: Right-click the page and choose encoding> new encoding> GBK (you cannot specify the encoding for your page, however, we need to prevent users from changing your encoding method in this way.
2. The server changes the encoding.
A) change the default encoding method of Tomcat: open the service in the conf folder under tomcat. search for 8080 in xml format and add URIEncoding = 'gbk' as follows: <Connector port = "8080" maxThreads = "150 "... URIEncoding = 'gbk'/>. In the instance, the default encoding method in step 3 is changed to GBK.
B) do not use the default TOMCAT encoding method to process parameters on the server, for example, in the Servlet
Protected void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String param = arg0.getParameter ("param ");
// The UTF-8 is the specified page encoding method, and the ISO-8859-1 is the default decoding method for TOMCAT (URIEncoding)
Param = new String (param. getBytes ("ISO-8859-1"), "UTF-8 ");
System. out. println (param );
//...
}
3. Use JavaScript code twice
String toTspt = "Chinese ";
// Encode the code twice. When using js, var params = "name =" + URIEncode (valueOfName) + "& age =" + ...;
String tempString = URLEncoder. encode (URLEncoder. encode (toTspt, "UTF-8"), "UTF-8 ");
// Transfer, the browser will not encode, because there are no special characters
System. out. println (tempString );
// Resolution. No matter what encoding method TOMCAT uses by default, it can be correctly decoded (no special characters)
TempString = URLDecoder. decode (tempString, "ISO-8859-1 ");
// Obtain the result
String resultString = URLDecoder. decode (tempString, "UTF-8 ");