JAVA character encoding Series 3: coding problems in Java applications

Source: Internet
Author: User
Article 3: JAVA character encoding Series 3: coding problems in Java applications this part adopts the reuse mechanism and references an article to complete this part. Source: Eceel Research -- character set encoding address: http://china.eceel.com/article/study_for_character_encoding_java.htm

1. Overview

This article mainly includes the following aspects: Basic coding knowledge, java, system software, url, tool software, etc.

In the following description, we will take the word "Chinese" as an example. We can see that its GB2312 encoding is "d6d0 cec4" and Its Unicode encoding is "4e2d 6587 ", the UTF code is "e4b8ad e69687 ". Note that the two words do not have iso8859-1 encoding, but they can be represented by iso8859-1 encoding ".

2. Basic coding knowledge

The earliest encoding was iso8859-1, which is similar to ascii encoding. However, many standard encodings have gradually emerged to facilitate representation of various languages. The following are important.

2.1. iso8859-1

It is a single-byte encoded string with a maximum character range of 0-255. It is used in English series. For example, the letter 'A' is encoded as 0x61 = 97.

It is obvious that the iso8859-1 encoding represents a narrow range of characters that cannot represent Chinese characters. However, because it is a single-byte encoding, and the computer's most basic representation unit, so many times, still use iso8859-1 encoding to represent. This encoding is used by default in many protocols. For example, although the word "Chinese" does not exist iso8859-1 encoding, The gb2312 encoding, for example, should be "d6d0 cec4" two characters, when using iso8859-1 encoding, it is split into 4 bytes to indicate: "d6 d0 ce c4" (in fact, it is also processed in bytes during storage ). For UTF Encoding, it is 6 bytes "e4 b8 ad e6 96 87 ". Obviously, this representation method also needs to be based on another encoding.

2.2. GB2312/GBK

This is the man's Country Code, specifically used to represent Chinese characters, is a dubyte encoding, while English letters and iso8859-1 consistent (compatible with iso8859-1 encoding ). Gbk encoding can be used to both traditional and simplified Chinese characters, while gb2312 can only represent simplified Chinese characters. gbk is compatible with gb2312 encoding.

2.3. unicode

This is the most unified encoding, which can be used to represent characters in all languages, and is a fixed-length dubyte (also four bytes) encoding, including English letters. So it can be said that it is not compatible with iso8859-1 encoding, is not compatible with any encoding. However, compared to iso8859-1 encoding, uniocode encoding only adds a 0 byte before, for example, the letter 'A' is "00 61 ".

It should be noted that fixed-length encoding is easy for computer processing (note that GB2312/GBK is not fixed-length encoding), while unicode can be used to represent all characters, therefore, many software programs use unicode encoding, such as java.

2.4. UTF

Considering that unicode encoding is not compatible with iso8859-1 encoding and is easier to use, unicode also requires two bytes for English letters. Unicode is not easy to transmit and store. Therefore, utf Encoding is produced. utf Encoding is compatible with iso8859-1 encoding and can also be used to represent characters in all languages. However, utf Encoding is not long encoding, the length of each character ranges from 1 to 6 bytes. In addition, utf Encoding comes with a simple verification function. Generally, English letters are represented in one byte, while Chinese characters are represented in three bytes.

Note: Although utf is used to use less space, it is undoubtedly the most economical to use GB2312/GBK if it is known to be Chinese characters as compared with unicode encoding. On the other hand, it is worth noting that although utf uses three bytes for Chinese characters, even for Chinese webpages, utf Encoding will save compared with unicode encoding, because the webpage contains many English characters.

3. java processing of Characters

In java application software, character set encoding is involved in many cases. In some cases, correct settings are required, and in some cases, certain processing is required.

3.1. getBytes (charset)

This is a standard function for java string processing. Its function is to encode the characters represented by the string according to charset and represent them in bytes. Note that strings are always stored in the java memory in unicode encoding. For example, if "Chinese" is stored as "4e2d 6587" under normal circumstances (I .e. when there is no error), if charset is "gbk", it is encoded as "d6d0 cec4 ", then return The Byte "d6 d0 ce c4 ". If charset is "utf8", it is "e4 b8 ad e6 96 87 ". If it is a "iso8859-1", "3f 3f" (two question marks) will be returned because it cannot be encoded ).

3.2. new String (charset)

This is another standard function for java string processing. In contrast to the previous function, it combines byte arrays according to charset encoding and finally converts them to unicode storage. Referring to the above getBytes example, "gbk" and "utf8" both can get the correct result "4e2d 6587", but the iso8859-1 finally becomes "003f 003f" (two question marks ).

Because utf8 can be used to represent/encode all characters, new String (str. getBytes ("utf8"), "utf8") = str, that is, completely reversible.

3.3. setCharacterEncoding ()

This function is used to set the http request or the corresponding encoding.

For request, it refers to the encoding of the submitted content. After specified, the correct string can be obtained directly through getParameter (). If not specified, the iso8859-1 encoding is used by default and needs further processing. See "form input" below ". It is worth noting that no getParameter () can be executed before setCharacterEncoding () is executed (). Java doc Description: This method must be called prior to reading request parameters or reading input using getReader (). This parameter is only valid for the POST method and invalid for the GET method. The cause of the analysis should be that when the first getParameter () is executed, java will analyze all submitted content according to the encoding, and the subsequent getParameter () will not be analyzed, so setCharacterEncoding () invalid. For the form submitted by the GET method, the submitted content is in the URL, and all submitted content has been analyzed according to encoding at the beginning. setCharacterEncoding () is naturally invalid.

For response, the encoding of the output content is specified. At the same time, this setting is passed to the browser to tell the browser the encoding of the output content.

3.4. handling process

The following two representative examples illustrate how java handles coding problems.

3.4.1. form input

User input * (gbk: d6d0 cec4) browser * (gbk: d6d0 cec4) web server iso8859-1 (00d6 00d 000ce 00c4) class, which needs to be processed in the class: getbytes ("iso8859-1") is d6 d0 ce c4, new String ("gbk") is d6d0 cec4, in memory in unicode encoding is 4e2d 6587.

L The encoding method entered by the user is related to the page-specific encoding and the user's operating system. Therefore, it is uncertain. The above example uses gbk as an example.

L from browser to web server, you can specify the character set used for content submission in the form. Otherwise, the encoding specified by the page will be used. What if I use it directly in the url? Input parameters, the encoding is usually the operating system code, because it is irrelevant to the page. The above uses gbk encoding as an example.

L The Web server receives a byte stream. By default, (getParameter) will be processed in iso8859-1 encoding, and the result is incorrect, so it needs to be processed. However, if the encoding (via request. setCharacterEncoding () is set in advance, the correct result can be obtained directly.

L it is a good habit to specify encoding on the page, otherwise it may be out of control and cannot be specified correctly.

3.4.2. File Compilation

Assume that the file is saved by gbk encoding, and there are two encoding options for compilation: gbk or iso8859-1, the former is the default encoding of Chinese Windows, the latter is the default encoding of linux, you can also specify the encoding during compilation.

Jsp * (gbk: d6d0 cec4) java file * (gbk: d6d0 cec4) compiler read uincode (gbk: 4e2d 6587; iso8859-1: 00d6 00d 000ce 00c4) compiler write utf (gbk: e4b8ad e69687; iso8859-1: *) compiled file unicode (gbk: 4e2d 6587; iso8859-1: 00d6 00d 000ce 00c4) class. Therefore, it is not correct to use gbk encoding to save and compile with iso8859-1.

Class unicode (4e2d 6587) system. out/jsp. out gbk (d6d0 cec4) OS console/browser.

L files can be saved in multiple encoding modes. In Chinese Windows, the default value is ansi/gbk.

L when the compiler reads a file, it needs to get the encoding of the file. If not specified, the system default encoding is used. Generally, the class file is saved in the default encoding of the system, so there will be no compilation problem. However, for jsp files, if they are edited and saved in Chinese windows, they will be deployed in English linux to run/compile, the problem may occur. Therefore, you must use pageEncoding to specify the encoding in the jsp file.

L during Java compilation, it will be converted to a unified unicode encoding process, and then converted to utf Encoding during storage.

L when the System outputs characters, it will output according to the specified encoding. For Chinese windows. for response (browser), The contentType specified by the jsp file header is used, or the encoding can be directly specified for response. At the same time, it will tell the browser webpage code. If not specified, iso8859-1 encoding is used. For Chinese characters, the encoding of the output string should be specified for browser.

L when browser displays the webpage, it first uses the encoding specified in response (the contentType specified in the jsp file header is also reflected in response). If not specified, the contentType specified by the meta item in the webpage is used.

3.5. Several settings

For web applications, encoding-related settings or functions are as follows.

3.5.1. jsp Compilation

Specify the storage encoding of the file. Obviously, this setting should be placed at the beginning of the file. For example, <% @ page pageEncoding = "GBK" %>. In addition, for general class files, encoding can be specified during compilation.

3.5.2. jsp output

Specifies the encoding used to output the file to the browser. This setting should also be placed at the beginning of the file. For example, <% @ page contentType = "text/html; charset = GBK" %>. This setting is equivalent to response. setCharacterEncoding ("GBK.

3.5.3. meta settings

Specifies the encoding used by the webpage. This setting is particularly useful for static webpages. Because static Web pages cannot use jsp settings and cannot execute response. setCharacterEncoding (). For example: <META http-equiv = "Content-Type" content = "text/html; charset = GBK"/>

If both jsp output and meta encoding are used, the jsp encoding takes precedence. Because the content specified by jsp is directly reflected in response.

Note that apache has a setting that allows you to specify the encoding for a webpage without encoding. This setting is equivalent to the jsp encoding method, so it overwrites the meta specified in the static webpage. Therefore, it is recommended that you disable this setting.

3.5.4. form settings

When the browser submits a form, you can specify the corresponding encoding. For example, <form accept-charset = "gb2312">. Generally, you do not need to use this setting. The browser uses the webpage encoding directly.

4. System Software

The following describes some related system software.

4.1. mysql database

Obviously, to support multiple languages, you should set the database encoding to utf or unicode, while utf is more suitable for storage. However, unicode is more suitable if there are few English letters in Chinese data.

The database encoding can be set through the mysql configuration file, for example, default-character-set = utf8. You can also set it in the database link URL, for example, useUnicode = true & characterEncoding = UTF-8. Note that both of them should be consistent. In the new SQL version, you can choose not to set the database link URL, but it cannot be an incorrect setting.

4.2. apache

Appache and encoding-related configuration in httpd. conf, for example, adddefacharcharset UTF-8. As mentioned above, this feature sets the encoding for all static pages to UTF-8, preferably disabling this feature.

In addition, apache has a separate module to process the webpage Response Header, which may also be used to set the encoding.

4.3. Default linux Encoding

The default linux encoding is the runtime environment variable. Two important environment variables are LC_ALL and LANG. The default encoding affects the behavior of java URLEncode, which is described below.

We recommend that you set it to "zh_CN.UTF-8 ".

4.4. Others

To support Chinese file names, linux should specify character sets when loading disks, such as mount/dev/hda5/mnt/hda5/-t ntfs-o iocharset = gb2312.

In addition, the information submitted using the GET method does not support request. setCharacterEncoding (), but the character set can be specified through the tomcat configuration file. xml file, such as: <Connector... URIEncoding = "GBK"/>. In this way, all requests are set in a unified manner, but not specific to the specific page. It is not necessarily the same as the encoding used by browser, so sometimes it is not expected.

5. URL address

It is very troublesome to include Chinese characters in the URL address. We have previously described how to submit a form using the GET method. When using the GET method, the parameter is included in the URL.

5.1. URL Encoding

The browser automatically encodes some special characters in the URL. Except "/? & ", Including unicode characters, such as man. The encoding is special.

IE has an option "always use UTF-8 to send URLs", when this option is valid, IE will perform UTF-8 encoding for special characters while URL encoding. If the modification option is invalid, the default encoding "GBK" is used without URL encoding. However, for parameters after a URL, it is always not encoded, which is equivalent to an invalid UTF-8 option. For example, "Chinese .html? A = Chinese ", when the UTF-8 option is valid, will send the link" %e4%b8%ad%e6%96%87.html? A = \ x4e \ x2d \ x65 \ x87 "; when the UTF-8 option is invalid, the link" \ x4e \ x2d \ x65 \ x87.html? A = \ x4e \ x2d \ x65 \ x87 ". Note that the character "Chinese" in front of the latter has only four bytes, but the former has 18 bytes. This is mainly due to URL encoding.

When web server (tomcat) receives this link, URL Decoding is performed, removing "%" and encoding by ISO8859-1 (as described above, you can use URLEncoding to set it to another encoding. The result of the above example is "\ ue4 \ ub8 \ uad \ ue6 \ u96 \ u87.html? A = \ u4e \ u2d \ u65 \ u87 "and" \ u4e \ u2d \ u65 \ u87.html? A = \ u4e \ u2d \ u65 \ u87 ", note that the word" Chinese "in front of the former is restored to six characters. Here, "\ u" is used to indicate unicode.

Therefore, due to different client settings and the same link, different results are obtained on the server. Many people have encountered this problem, but there is no good solution. Therefore, some websites recommend that users try to disable the UTF-8 option. However, the following describes a better solution.

5.2. rewrite

As we all know, apache has a powerful rewrite module, which is not described here. It must be noted that this module will automatically decode the URL (remove %) to complete some of the above web server (tomcat) functions. The [NE] parameter can be used to disable this function. However, I did not test the function successfully, probably because of the version (apache 2.0.54 is used. In addition, when the parameter contains "? And other symbols, this function will cause the system to fail to get the normal results.

Rewrite itself seems to adopt the byte processing method completely without considering the character string encoding, so it will not bring about Encoding Problems.

5.3. URLEncode. encode ()

This is the URL encoding function provided by Java itself, and the work done is similar to the work done by the browser when the above UTF-8 options are valid. It is worth noting that java does not approve of using this method (deprecated) without specifying encoding ). Encoding should be added during use.

If no encoding is specified, this method uses the system default encoding, which leads to uncertain software running results. For example, for "Chinese", when the system default encoding is "gb2312", the result is "% 4e % 2d % 65% 87", and the default encoding is "UTF-8 ", the result is "% e4 % b8 % ad % e6 % 96% 87", which will be difficult to handle in the future. In addition, the default system encoding is determined by the environment variables LC_ALL and LANG when tomcat is running. Once tomcat is restarted, garbled characters occur, the last depressing result was that the two environment variables were modified.

It is recommended that you specify it as a "UTF-8" encoding in a unified manner, and you may need to modify the corresponding program.

6. Others

The following describes some encoding-related issues.

6.1. SecureCRT

In addition to coding, browsers and consoles are also related to some clients. For example, when using SecureCRT to connect to linux, the display encoding of SecureCRT should be consistent with that of linux encoding environment variables (different sessions can have different encoding settings. Otherwise, some help information may be garbled.

In addition, mysql has its own encoding settings and should also be consistent with the display encoding of SecureCRT. Otherwise, Chinese characters may not be processed when SQL statements are executed using SecureCRT, and garbled characters may appear in the query results.

For Utf-8 files, many editors (such as NotePad) add three invisible flag bytes at the beginning of the file, and if you are an mysql input file, you must remove these three characters. (You can remove these three characters when saving them with linux vi ). An interesting phenomenon is that in Chinese Windows, create a new txt file, open it in notepad, enter the word "Connect", save it, and open it again. You will find that the two words are gone, only one small black spot is left.

6.2. Filter

If you need to set the encoding in a unified manner, it is a good choice to set the encoding through the filter. In filter class, encoding can be set for all requests or responses. Participate in the above setCharacterEncoding (). This type of apache has provided an example that can be directly used: SetCharacterEncodingFilter.

6.3. POST and GET

Obviously, when submitting information via POST, the URL is more readable, and setCharacterEncoding () can be easily used to handle Character Set problems. However, the URL formed by the GET method can easily express the actual content of the webpage and be used for favorites.

From a unified perspective, we recommend that you use the GET method, which requires special processing to obtain parameters in the program, rather than using setCharacterEncoding (). If you do not consider rewrite, there is no UTF-8 problem with IE, you can consider setting URIEncoding to easily get parameters in the URL.

6.4. Simplified and Traditional Chinese encoding conversion

GBK also contains both simplified and traditional Chinese characters. That is to say, the same word belongs to two characters under GBK encoding because of different codes. Sometimes, in order to get the complete results correctly, we should unify the Traditional Chinese and simplified Chinese. You can consider converting all traditional Chinese characters in UTF and GBK into simplified Chinese characters. BIG5 encoding data should also be converted into simplified Chinese characters. Of course, it is still stored in UTF Encoding.

For example, for "language statement", UTF is used to indicate "\ xE8 \ xAF \ xAD \ xE8 \ xA8 \ x80 \ xE8 \ xAA \ x9E \ xE8 \ xA8 \ x80 ", after the simplified and traditional encoding is converted, it should be two identical "\ xE8 \ xAF \ xAD \ xE8 \ xA8 \ x80> ".

Related Article

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.