The ultimate solution to various Chinese garbled characters of JavaWeb in those years

Source: Internet
Author: User
Tags set cookie

I. Servlet output garbled characters
1. Use the servlet. getOutStream byte stream to output Chinese characters. Suppose the output is String str = "the Diaoyu Islands are from China, and the shameless is from Japan ".
1.1 If the local server and the local client are the same, you can directly output out. write (str. getBytes. Because str. getBytes () is used in the server as the default local encoding, such as GBK. The browser also uses the local default encoding for parsing. The two are uniform, so there is no problem.
1.1 If the server output is used, out. write (str. getBytes ("UTF-8 ")). When the local default encoding is GBK (the proportion is in China), it will be garbled when opened in a browser. Because the server sends 1010 of UTF-8 data, and the client browser uses gbk for decoding, the encoding is not uniform, and it must be garbled. Of course, you can also manually call the encoding of the client browser (the IE menu is: query View-> encoding-> UTF-8), but this operation is very bad, it is best for the server to output a response header to tell which encoding the browser uses to decode. Therefore, add response in the servlet of the server. setHeader ("content-type", "text/html; charset = UTF-8"), of course, you can also directly use a simple response. setContentType ("text/hmtl; charset = UTF-8 "). The two operations are the same.
2. Use servlet. getWirter logs to output Chinese characters. Assume that the output is String str = "the Diaoyu Islands are from China, and the shameless is from Japan ".
2.1 If the output is output by output. print (str), the client browser displays multiple ????? Character, indicating that the corresponding characters cannot be found in the encoding table. The reason is: servlet. getWriter () to get the character output stream, by default the output of the character is ISO-8859-1, and ISO-8859-1 is certainly not support Chinese. Therefore, the first thing to do is to output characters from the server object to support Chinese characters. Second, the Response Header written back from the server to the client should tell the client which encoding table is used. To meet these two requirements, you only need response. setContentType ("text/hmtl; charset = UTF-8 "). That's it. Special note: response. setContentType ("text/html; charset = UTF-8") should be placed in PrintOut out = response. before the getWriter () code, otherwise there is only a function to tell the client what code table encoding, and the server side is still coded with a ISO-8859-1. Note: In the doGet or doPost method of the same Servlet, the response cannot be used. getOutputStream uses response again. getWriter, because the response output byte stream of the two response types conflicts with the response stream, only one of them can be used.
Ii. Servlet File Download. Chinese characters are garbled.
The key is the attachment; filename = file name in the response header content-disposition during download. This file name filename cannot contain Chinese strings. It must be encoded by URLEncoding before http transmission. Example code:
[Java] view plaincopy
// Obtain the URL of the object
String realPath = getServletContext (). getRealPath ("/diaoyudao is China's shameful historical evidence of Japan. jpg ");
// Get the file name: diaoyudao is China's shame, and it is the historical evidence of Japan. jpg
String fileName = realPath. substring (realPath. lastIndexOf ("\") + 1 );
// Indicates that the response stream type is not text/html but binary stream data to indicate download.
Response. setContentType ("application/octet-stream ");
// Note that the URLEncoder encode method is generally used to encode the file name.
String enFileName = URLEncoder. encode (fileName, "UTF-8 ");
// If the enFileName file name contains Chinese characters, URLEncoding must be used for encoding.
Response. setHeader ("content-disposition", "attachment; filename =" + enFileName );
// File Read and output, template code...
InputStream in = new FileInputStream (realPath );
OutputStream out = response. getOutputStream ();
Int len =-1;
Byte [] buf = new byte [1, 1024];
While (len = in. read (buf ))! =-1 ){
Out. write (buf, 0, len );
}
In. close ();

3. Add addCookie to Servlet response and solve the problem of the Chinese Code of the value in cookie.
For how cookies work, see http://blog.csdn.net/chenshufei2/article/details/8009992. To store Chinese characters in the cookie, you must use Base64 encoding and send it to the client browser for storage. The next client access is the value in the returned cookie, Which is base64-encoded. Therefore, Base64 decoding is required. Base64 encoding is mainly used to re-encode special characters into a-B, A-B, 0-9, + and/. The characters are and 10 digits plus one +, A total of 64 characters. The principle is to encode the content of the original three bytes into four bytes. It is mainly to take the 6-byte back and add 00 to form a new byte. Therefore, the original 3 bytes are 24 in total and are encoded into 4 bytes and 32 bits.
The code example is as follows:
[Java]
Response. setContentType ("text/html; charset = UTF-8 ");
Request. setCharacterEncoding ("UTF-8 ");
String getUserName = request. getParameter ("username ");
PrintWriter out = response. getWriter ();
String username = null;
// Obtain the cookie array submitted by the client.
Cookie [] cookies = request. getCookies ();
For (int I = 0; cookies! = Null & I <cookies. length; I ++ ){
// Traverse the cookie array and find the cookie containing the key of username.
If (Constant. USER_INFO.equals (cookies [I]. getName ())){
Username = cookies [I]. getValue ();
// Base64 decoding is required after the cookie value is obtained, because the value is base64-encoded during the previous cookie generation.
Username = Base64Coder. decode (username); // perform Base64 Decoding
}
}
 
Out. print (username + ", congratulations on your logon success..." + getUserName); // username is obtained from the Cookie and getUserName is included in the request parameter
System. out. println (username + "------------");
String remember = request. getParameter ("remember ");
// Chinese characters must be encoded with base64 to be used as the cookie value.
GetUserName = Base64Coder. encode (getUserName );
// Use the Encoded chinese username as the cookie value
Cookie cookie = new Cookie (Constant. USER_INFO, getUserName );
Cookie. setPath (getServletContext (). getContextPath ());
If (null! = Remember) {// if selected, the Cookie is written. If not selected, the previous Cookie is left empty.
Cookie. setMaxAge (Integer. MAX_VALUE); // set Cookie to the maximum number of Integer values, as if it had been valid for more than 70 years. Haha
} Else {
Cookie. setMaxAge (0); // set the cookie to expire immediately. maxAge indicates the cookie survival time.
}
Response. addCookie (cookie );

4. garbled Request Parameters
Garbled GET:
For example, <a href = "/demo5/servlet/RD2? Name = China "> CN </a>, directly use request. the strCN string obtained by getParameter will be garbled, because the GET method is passed through the http url and is encoded by iso-8859-1 by default, so the first get strCn to use iso-8859-1 encoding to get the original, and then use UTF-8 (see the specific page of charset what is UTF-8 or gbk) decoding can be. New String (strCn. getBytes ("ISO-8859-1"), "UTF-8 ");
[Java
String strCn = request. getParameter ("name ");
String name = new String (strCn. getBytes ("ISO-8859-1"), "UTF-8 ");
This method of operation is more troublesome, there is a parameter to use iso-8859-1 encoding and decoding again.
POST mode garbled: only request. setCharacterEncoding ("UTF-8.
[Java]
Request. setCharacterEncoding ("UTF-8 ");
String name = request. getParameter ("name ");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.