Java Chinese garbled solution

Source: Internet
Author: User

The JVM internal code uses Unicode encoding.

Common character encoding set: ASCII encoding, GBK encoding, Unicode encoding

UTF-8 is just one way to implement Unicode;

One of the biggest features of UTF-8 is that it is a variable-length coding method. It can use 1~4 bytes to represent a symbol, varying the length of a byte depending on the symbol.

The coding rules for UTF-8 are simple, with only two lines:
1) for a single-byte symbol, the first bit of the byte is set to 0, and the next 7 bits are the Unicode code for the symbol. So for the English alphabet, the UTF-8 encoding and ASCII code are the same.
2) for n-byte notation (n>1), the first n bits are set to 1, the n+1 bit is set to 0, and the first two bits of the subsequent bytes are set to 10. The rest of the bits are not mentioned, all of which are Unicode codes for this symbol.

Unicode encoding, which uses double-byte encoding, compatible with English characters and the double-byte character encoding of other national nationalities.

The reason why the garbled is generated:

Each country in order to unify the code will stipulate that the country/region computer Information interchange with the character set encoding, in order to solve the local character information computer processing, so there are a variety of localized versions, introduced Lang, Codepage and other concepts. Most of the software core character processing with internationalized features is now based on Unicode, which determines the local character encoding settings based on the Locale/lang/codepage settings at the time of the software operation and handles local characters accordingly. The conversion between Unicode and local character sets is required during processing.

In the same way, the Java internal use of Unicode encoding, so in the process of Java will inevitably exist from the Unicode encoding and the corresponding computer operating system or browser-supported encoding format of the conversion process, this conversion process has a series of steps, if a step error, Then the output text will be garbled.

So the problem with Java garbled is that the JVM has an error encoding format conversion with the corresponding operating system/browser.

In fact, to solve the problem of Java garbled method is relatively simple, but to investigate its reasons, the principle behind understanding is still need to understand

In fact, the method of solving the Chinese character coding problem in JAVA program is often very simple, but understanding the reason behind it, locating the problem, also need to understand the existing Chinese character coding and encoding conversion.

Basic Knowledge:

Coding : Encoding is the process of converting information from one form or format to another, and the common example of ' Chen ' in the computer is how to express, the process is coding;

decoding: Is the inverse process of the code, the binary system of the computer into the text or picture information that we can understand;

Java Encoding conversion process:

Life cycle:

1. Programmers write program code through the editor on the operating system and save the operating system in. java format, which we call source files.

2. Compile these source files from the Javac.exe in the JDK to form a. Class.

3. Run these classes directly or deploy them in a web container to get the output results.

The main process:

The first step: When we use the editor to write Java source files, the program file will be saved with the operating system default encoding format (generally our Chinese operating system using the GBK encoding format) to form a. java file. Java source files are saved in the File.encoding encoding format, which is supported by the operating system default. The following code can view the system's file.encoding parameter values.

System.out.print (System.getproperty ("file.encoding"));

Step Two: When we compile our Java file using Javac.exe, the JDK first confirms its compilation parameter encoding to determine the source code character set, and if we do not specify that compilation parameter, the JDK first obtains the operating system default file.encoding parameter, then the JDK will write our Java source The program is converted from the File.encoding encoded format to the Java internal default Unicode format into memory.

Step Three: The JDK writes the above compiled and saved in-memory information to the class file, creating a. class file. At this point, the. class file is Unicode encoded, meaning that the contents of our common. class files are converted to Unicode encoding format, whether they are Chinese characters or English ones.

In this step, the JSP source files are treated a little differently: the Web container calls the JSP compiler, the JSP compiler will first see if the JSP file is set in the file encoding format, If not set, the JSP compiler invokes the calling JDK to convert the JSP file into a temporary servlet class using the default encoding, and then compiles it into a. class file and remains in the Temp folder.

Fourth Step: Run the compiled class: there are a few situations here (where garbled occurrences are common)

1. Run directly on the console.

2, Jsp/servlet class.

3, between the Java class and the database.

Each of these three cases will be different in the same way, the class running on 1.Console

In this case, the JVM first reads the class file stored in the operating system into memory, when the in-memory class file is encoded in Unicode and the JVM runs it. If a user is required to enter information, the information entered by the user is encoded in the File.encoding encoding format and converted to the Unicode encoding format to be saved to memory. After the program is run, the resulting results are converted to the file.encoding format and returned to the operating system and exported to the interface. The entire process is as follows:

Since JSP files are eventually converted to servlet files (except where they are stored), we also include JSP files here.

When a user requests a servlet, the Web container invokes its JVM to run the servlet. First the JVM loads the servlet's class into memory, and the servlet code in memory is in Unicode encoded format. The JVM then runs the servlet in memory, and if it needs to accept data passed from the client (such as forms and URL-passed data) during the run, the Web container will accept the incoming data, and in the receiving process, if the program sets the encoding of the passed parameters in the encoded format, If not set, the default iso-8859-1 encoding format is used, and after the data is received, the JVM converts the data to Unicode and is stored in memory. Output results are generated after the servlet is run, and the encoding format for these outputs is still Unicode. The Web container then sends the resulting Unicode encoded string directly to the client, and if the program specifies the encoding format for the output, it is output to the browser in the specified encoding format, otherwise the default iso-8859-1 encoding format is used. The entire process flow chart is as follows:

We know that Java programs are connected to the database through the JDBC driver, and the JDBC driver defaults to the ISO-8859-1 encoded format, which means that when we pass data to the database through a Java program, JDBC first converts data in Unicode encoded format to ISO-8859-1 encoded format, and then stores it in a database, that is, the default format is iso-8859-1 when data is saved in the database.

Common Coding & Decoding scenarios:

There are four main scenarios in Java that require encoding and decoding operations:

1:I/O operation

2: Memory

3: Database

4:javaweb (Network transport) I/O operations

1. In front of the garbled problem is nothing more than the transcoding process in the encoding format of the non-uniform generation, such as the use of UTF-8 encoding, decoding using GBK, but the most fundamental reason is the character to byte or byte-to-character conversion problem, and this situation of the most important scenario is the time I/O operation. Of course I/O operations mainly include network I/O (i.e. javaweb) and disk I/O. The following section describes the network I/O.

Network Transmission:

The user wants the server to send an HTTP request, where there is a URL, a cookie, a parameter, the encoded server accepts the HTTP request, parses the HTTP request, and decodes the URL, cookie, parameter. It is possible to read the database, local files, or other files on the network in the course of the server's business logic processing, all of which require encoding and decoding. When processing is complete, the server encodes the data and sends it to the client, which is decoded and displayed to the user. In this whole process involved in encoding decoding more places, wherein the most prone to garbled location is the server and the client to interact with the process.

Above the entire process can be summed up in this way, the page encoding data to the server, the server to obtain the data decoding operation, after a business logic processing after the final result encoding processing to the client, the client decoding display to the user. So I'm going to ask for the code & decoding of Javaweb.

The client wants the server to send a request with nothing but four things:

1, direct access to the URL method.

2, page links.

3. Form Get submit

4. Form Post Submission

Server decoding is bound to cause a lot of trouble, below we will have Tomcat, see how tomcat is the URL decoding operation.

The URL to parse the request is in the Parserequestline method of Org.apache.coyote.HTTP11.InternalInputBuffer, which sets the byte[of the URL passed in to org.apache.co. Yote. The corresponding attribute of the Request. The URL here is still in byte format, and turning to Char is done in Org.apache.catalina.connector.CoyoteAdapter's Converturi method:

From the above code, the decoding operation of the URI is to get the decoding set of connector first, which is in Server.xml

<connector uriencoding= "Utf-8"/>

If not defined, it is parsed using the default encoding iso-8859-1.

For the query string section, we know that whether we commit by GET or post, all parameters are saved in parameters, Then we pass the Request.getparameter, the decoding work is the first time when the GetParameter method is called. Inside the GetParameter method, it calls the Org.apache.catalina.connector.Request Parseparameters method, which decodes the passed arguments. The following code is only part of the Parseparameters method:

From the code above, we can see that the decoding format of query string either takes the set Chartset or the default decoding format iso-8859-1. Note that the chartset of this setting is the contenttype defined in the HTTP header, and if we need to change the specified attribute to take effect, we need to configure the following: Form get

We know that submitting data by URL is prone to garbled problems, so we are more inclined to form forms. When the user clicks on the Submit form, the browser will encode the data to the server with a more set encoding. Data submitted by get is stitched behind the URL (can be used as query String??). ) to commit, so the Tomcat server uriencoding during the decoding process. The Tomcat server is decoded according to the set uriencoding, and if not set, it is decoded using the default iso-8859-1. If we set the encoding to UTF-8 on the page, and the uriencoding setting is not or not set, then the server will be garbled when decoding. At this time we can generally get the correct data through the form of new String (Request.getparameter ("name"). GetBytes ("Iso-8859-1"), "Utf-8".

Form Post

For post, the encoding it uses is also determined by the page, which is contenttype. When I submit a form by clicking the Submit button on the page, the browser first encodes the parameters of the post form and submits it to the server according to the Ontenttype CharSet encoding format. On the server side is also used in the ContentType set of character sets to decode (here and get method is different), this is the post form submitted by the parameters are generally not garbled problem. Of course, this character set encoding we can set ourselves: Request.setcharacterencoding (CharSet).

JSP page encoding Process

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" GBK "%>

In the above code there are two places encoded: pageencoding, ContentType CharSet. Where pageencoding is the encoding of the JSP file itself, and ContentType's charset refers to the content encoding when the server is sent to the client.

First time: Convert to. java files;

Second time: Convert to. class file;

The third time: After the business logic is processed output.

The first step: the JVM compiles the JSP into a. jsp file. In this process, pageencoding plays a role, the JVM first gets the value of pageencoding, if the value exists, it is compiled with the encoding it sets, otherwise it is compiled with file.encoding encoding.

Step two: The JVM converts the. java file to a. class file. This process is not related to any encoding settings, no matter what encoding format the JSP uses. After this phase, the. jsp file is converted to a. class file in a unified Unicode format.

The background is processed by the business logic to output the resulting results to the client. In this process, the ContentType charset has been effective. If CharSet is set, the browser is decoded using the specified encoding format, otherwise it is decoded with the default iso-8859-1 encoding format.

The process is as follows:

The location where garbled characters occur:

Javascript

Use JavaScript to encode the opportunity to not interfere with the browser, encode and then send the request to the server, and then decode the server. In mastering this approach, we need three ways to encode javascript: Escape (), encodeURI (), encodeURIComponent ().

Converts the URI string into an escape format using the UTF-8 encoding format. More powerful than encodeuri,encodeuricomponent, it will be for those symbols that are not encoded in encodeURI (; / ? : @ & = + $, #) will all be encoded. However, encodeuricomponent only encodes the part of the URL individually, not the entire URL. Corresponding decoding function method decodeuricomponent.

Java Chinese garbled solution

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.