Tomcat garbled reason: When learning the servlet, often encounter Chinese garbled problem, online check only know how to set not garbled, the principle is not very clear. I think understand the principle, garbled problem is easy to solve
Tomcat garbled Solution:
POST request:
Request.setcharacterencoding ("Utf-8");
Write a filter if you don't want to write in every request method
GET Request:
1. Modify the Server.xml file in Tomcat
<connector port= "8080" maxthreads= "75" minsparethreads= "maxsparethreads="
Enablelookups= "false" redirectport= "8443" acceptcount= "100"
connectiontimeout= "20000" disableuploadtimeout= "true" uriencoding= ' UFT-8 ' />
2. The get parameter is through the new String () method
String name = Request.getparameter ("name");
name = new String (name.getbytes ("iso-8859-1"), "Utf-8");
Problem: Tomcat uses the ISO-8859-1 encoding for GET requests, the encoding you set is used by default for post requests, and the default iso-8859-1 encoding is not set.
The POST request set encoding will not garbled, the principle is to use utf-8 encoding, using utf-8 decoding, do not use UTF-8 decoding will be error as follows:
New String ("Hello". GetBytes (), "Utf-8"); System.out.println (new string (S.getbytes (), "iso-8859-1"new string (S.getbytes (), " Utf-8 "); System.out.println (S1);
Results: Ľ好
How are you doing
Get request browser encoding is Utf-8, but Tomcat uses iso-8859-1 decoding will be garbled, why this can solve garbled,
Because the ISO-8859-1 encoding is a single-byte encoding, the direct array that is obtained using s1.getbytes ("Iso-8859-1") is the same as when it was not previously decoded.
So the use of Utf-8 is the same as the above post, just encode, decode
Not all garbled can be used this way, just because ISO-8859-1 encoding is a single-byte encoding, get its byte array is not changed
New String ("Hello". GetBytes (), "Utf-8"); System.out.println (Arrays.tostring (S.getbytes ())); // equivalent to tomcat help decoding New String (S.getbytes (), "iso-8859-1"); // print ISO-8859-1 encoded byte data, compared to the byte array before decoding, found as, so decoding with UTF-8 encoding is not garbled System.out.println (Arrays.tostring (S1.getbytes ("iso-8859-1"new String (S1.getbytes ("iso-8859-1 ")," Utf-8 "); SYSTEM.OUT.PRINTLN (S2);
Results:
[-28,-67,-96,-27,-91,-67]
[-28,-67,-96,-27,-91,-67]
How are you doing
Tomcat garbled reason--basic coding problem