Solve the problem of Chinese garbled characters output by httpservletresponse

Source: Internet
Author: User

 

Http://blog.csdn.net/simon_1/article/details/9092747

 

First, there are two types of response returned: one is the byte stream outputstream and the other is the bytes stream printwrite.

Declaration: For convenience, all outputs are coded in UTF-8.

First, let's talk about the byte stream. to output "China", the output stream must be "China" converted to UTF-8, And the browser must be told to parse the data using utf8.

 

Note: Response. setheader ("Content-Type", "text/html; charset = UTF-8 ");
To be written in: printwriter PW = response. getwriter (); or: outputstream PS = response. getoutputstream ();!!!!! Before !!!!!

 

[HTML]View plaincopy
  1. // This sentence means that the browser uses utf8 to parse the returned data
  2. Response. setheader ("Content-Type", "text/html; charset = UTF-8 ");
  3. String data = "China ";
  4. Outputstream PS = response. getoutputstream ();
  5. // The meaning of this sentence, so that the data into the stream is in utf8 format
  6. PS. Write (data. getbytes ("UTF-8 "));


Besides, to output the response stream to China, you need to set response. setcharacterencoding ("UTF-8 ");

[HTML]View plaincopy
  1. // This sentence means that the browser uses utf8 to parse the returned data
  2. Response. setheader ("Content-Type", "text/html; charset = UTF-8 ");
  3. // The meaning of this sentence is to tell the servlet to use the UTF-8 for transcoding, instead of using the default iso8859
  4. Response. setcharacterencoding ("UTF-8 ");
  5. String data = "China ";
  6. Printwriter PW = response. getwriter ();
  7. PW. Write (data );

 


Experience: 1. If the returned result is ?? Character, which indicates that response. setcharacterencoding ("UTF-8"); is not added.

2. If the returned Chinese characters are garbled characters such as "Invalid Response", it indicates the browser's parsing problem. Check whether the response is missing. setheader ("Content-Type", "text/html; charset = UTF-8.

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.