JavaWeb servlet, garbled causes and solutions

Why would request garbled?

  A: When the form is submitted, the browser on the Chinese parameter values ​​are encoded (using the character set to open a page where a form is coded, web server by default iso-8859-1 will be used to decode, encode and decode way inconsistent , will produce garbled.

Solution: request.setCharacterEncoding ( "UTF-8" ); to get even find files in tomcat server conf directory server.xml file folder, opens as follows .

 

 

 

How to check the character set encoding of the page?

 

Figure in the red box says that page's character set form where, at this time because the form of the character set is iso-8859-1 so the server would not set decoding way, Chinese are still not garbled.

response response back to the browser appears Chinese garbled?

  getOutputStream();:

    Using the output stream of bytes, can not be directly output Chinese, will be abnormal, to output Chinese, the following solution

    Solve: getOutputStream () write (xxx.getBytes ( "UTF-8")); // manually Chinese code table in UTF-8 encoding, into byte transfer, into the byte, it will not reported abnormal and tomcat are not in code, as it has been encoded, so the browser after,

                                If the browser using the UTF-8 code table to decode, then it will not appear garbled Chinese, and vice versa Chinese garbled appeared, so this method does not fully guarantee Chinese garbled

  getWrite () ;:

    Use character-output stream can be directly output Chinese, not the exception, but garbled.

    Solution: tomcat and inform the browser to use the same code table.

    response.setContentType ( "text / html; charset = utf-8"); // notify the browser uses UTF-8 decoding 

    Tomcat and inform the browser to use UTF-8 encoding and decoding. The underlying principle of this method is that the phrase: response.setHeader ( "contentType", "text / html; charset = utf-8"); 

  Note: getOutputStream () and getWrite () These two methods can not be used simultaneously, can use only one, otherwise reported abnormal    

 

Guess you like

Origin www.cnblogs.com/Tony100/p/11460965.html