1. Chinese garbled java web notes, 1. javaweb
Troubleshoot java web garbled issues
During Java Web development, garbled characters are frequently encountered, which leads to garbled characters. In summary, character encoding and decoding methods do not match.
Since the garbled characters do not match the character encoding and decoding methods, why do we need to encode the characters without encoding? This is because the basic unit of data storage in a computer is 1 byte, that is, 8 bits, so it can express a maximum of 28 = 256 characters, in our real society, the characters (Chinese characters, English letters, other words, and so on) are far redundant. To solve the conflict between characters and bytes, character encoding can be stored in the computer.
Encoding and decoding
Common coding methods in computer include ASCII, ISO-8859-1, GB2312, UTF-16, UTF-8.
The ASCII code is represented by a byte with a low 7-bit value. Therefore, a maximum of 27 = 128 characters can be expressed. ISO-8859-1 is ISO organization based on ASCII code extension, compatible with ASCII code, covers most Western European characters. The ISO8859-1 is represented in one byte, so it can express up to 256 characters. GB2312, using double byte encoding, encoding range is A1-F7, where A1-A9 is the symbol area, B0-F7 is the Chinese character area, contains 6763 Chinese characters. GBK is used to expand the GB2312 encoding and add more Chinese characters. There are 21003 Chinese characters that can always be expressed. UTF-16 is a fixed length encoding method, No matter what characters are expressed in 2 bytes, this is also the storage format of characters in JAVA memory. In contrast to the UTF-16, The UTF-8 uses a variable-length encoding method, and different types of characters can consist of 1-6 bytes.
The following uses the string "day-to-day" to check the encoding methods in the computer, as shown in.
Garbled Analysis and Solution
For java web garbled characters, we divide requests to cause garbled characters and responses. For different garbled characters, we need to analyze the causes of garbled characters, that is, the character encoding method, what is the decoding method.
For requests that cause garbled characters, we need to analyze Http requests and check their encoding methods. As HTTP requests are divided into Get requests and Post requests, we will discuss them separately.
Get requests are the default Request Method of the browser, and are set to "Get" when the form is submitted. We can view the following details through Firefox:
The address bar is:
Request content:
Through the above request, we can see that the query strings in the GET request are stored in the request line and sent to the WEB server. We can see that the query strings are encoded by "day-to-day, the browser uses the encoding method for this string as "UTF-8 ".
View the server code we can see garbled code (such as), because the server receives the string encoding after the data is decoded by default through the ISO-8859-1, therefore, the encoding and decoding methods are inconsistent.
The solution is as follows:
First, obtain the encoding before decoding the string user, and then specify the encoding method of the string, such:
The solution is as follows:
In the Java web development process, we transmit parameters in hyperlinks and often encounter Chinese characters. In this case, we need to encode Chinese, we can set to UTF-8, the decoding scheme is the same as above.
<A href = "$ {pageContext. request. contextPath}/Test? User = <% = URLEncoder. encode ("", "UTF-8") %> "> click </a>
For Post requests, it is the submission method when the form is set to "Post. We can view the following details through Firefox:
The address bar and its page are:
THE post request content is:
We can know that in the post request, the request content is directly placed in the Request body and sent to the web server. The encoding method is UTF-8 ".
In this response Servlet, The doPost method is as follows:
Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String user = request. getParameter ("user"); System. out. println (user); // The output is ¥ **=°}
The reason for garbled here is still in the Code getParameter ("user"), the web server uses the default decoding scheme "ISO-8859-1" for decoding, leading to the difference between the encoding and decoding scheme, the solution can adopt the get request garbled solution, but there is also a simpler solution to directly specify the encoding/decoding scheme of the method body as "UTF-8 ". The solution is as follows.
Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setCharacterEncoding ("UTF-8"); // set the request body encoding/decoding scheme to UTF-8, but the request line encoding and decoding scheme will not be affected String user = request. getParameter ("user"); System. out. println (user); // The output is from day to day}
The above analysis of the garbled characters caused by requests is complete.
In the Garbled text caused by the impact, the web server will write the response content into the response body and return the content to the client will not involve the status line. As shown in the response to "HelloWorld" output to the browser.
We have to deal with four methods for response-caused Garbled text, as shown below:
Response. setHeader ("Content-Type", "text/html; cahrset = UTF-8 "); // set the content type of the response sent to the client and the encoding type of the response content (the encoding type of the response body)
Response. setCharacterEncoding ("UTF-8"); // you can specify the encoding type of the response body.
Response. getWriter (); // get response Output response stream response. getOutputStream (); // get response output byte stream
Set the encoding type of the response body, such as response. setHeader ("Content-Type", "text/html; cahrset = UTF-8"); and response. setCharacterEncoding ("UTF-8"); these two methods are set to an equivalent encoding method. If no encoding method is set for the response body, the default is the ISO-8859-1, in addition, the encoding method of the response body character will iterate the preceding encoding method. Both methods are valid before the getWriter method. The encoding method set in the getWriter method is invalid.
However, the two methods are a bit different, that is, setHeader ("Content-Type", "text/html; cahrset = UTF-8 ") in this method, the browser automatically uses the encoding method of the response body for decoding, and setCharacterEncoding (). Not all browsers use this method for decoding, to test the two methods, the effect is as follows:
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setHeader ("Content-Type", "text/html; charset = UTF-8"); response. getWriter (). write (" ");}
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setCharacterEncoding ("UTF-8"); response. getWriter (). write (" ");}
We can see from the above that the first method supports better for the browser. We recommend that you use the first method to set the character encoding method of the response body.
For methods to get the response character output stream, if no encoding method is set for the response body before, the default value is null, that is, encoding in the ISO-8859-1 mode. The subsequent encoding method will overwrite the preceding encoding method. The encoding set after the getWriter () method is invalid.
For retrieving the response output byte stream, we need to set the encoding method of the string when outputting the string, if not then the default ISO-8859-1.
For the first two output streams, since there is only one output cache, the two methods are mutually exclusive.
Above, in order to ensure that the response is free of garbled characters, the character encoding and decoding methods must be unified. The solution is as follows:
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// solution 1 // response. setHeader ("Content-Type", "text/html; charset = UTF-8"); // response. getWriter (). write (""); // solution 2 // response. getOutputStream (). write (" ". getBytes ("UTF-8"); // Scheme 1, 2 mutex}
In addition, during Java web development, we also encounter problems caused by Chinese file names when downloading files, as shown in:
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String realPath = this. getServletContext (). getRealPath ("/src/ .jpg"); String fileName = realPath. substring (realPath. lastIndexOf ('\') + 1); response. setHeader ("content-disposition", "attachment; filename =" + fileName); InputStream is = new FileInputStream (new File (realPath); OutputStream OS = response. getOutputStream (); byte [] buff = new byte [1024]; int len = 0; while (len = is. read (buff)> 0) {OS. write (buff, 0, len);} OS. close (); is. close ();}
The Firefox browser is used for testing to view the page effect and the response results are as follows:
After viewing the response header analysis, the download file name is stored in the response header, and the Chinese text is not using UTF-8, UTF-16, GBK and so on can recognize Chinese encoding, which encoding method is used for the Chinese file name? Check REF 7578 and learn that ASCII code is used here, But REF specifies that if non-ASCII characters are to be used inevitably, the programmer should use the UTF-8 evenly, to minimize interactions.
So the solution is to encode the file name into a UTF-8 and pass it to the response header, and the browser (Part) decodes the file name by default.
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String realPath = this. getServletContext (). getRealPath ("/src/ .jpg"); String fileName = realPath. substring (realPath. lastIndexOf ('\') + 1); String utf_8Name = URLEncoder. encode (fileName, "UTF-8"); // solution response. setHeader ("content-disposition", "attachment; filename =" + utf_8Name); InputStream is = new FileInputStream (new File (realPath); OutputStream OS = response. getOutputStream (); byte [] buff = new byte [1024]; int len = 0; while (len = is. read (buff)> 0) {OS. write (buff, 0, len);} OS. close (); is. close ();}
The effect is as follows: Firefox does not decode it.
At last, I enjoyed my wife's beautiful photos: