Difference between esponse. setcontenttype and request. setcharacterencoding
1. Request. setcharacterencoding () indicates the value obtained from the request or retrieved from the database.
You can get the correct string directly through getparameter () after specifying, if not specified, iso8859-1 encoding is used by default. It is worth noting that no getparameter () can be executed before setcharacterencoding () is executed (). 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 the content has been analyzed and submitted according to the encoding at the beginning. setcharacterencoding () naturally does not work.
Get must be in Tomcat server. xml:
Uriencoding = "GBK"/>) added uriencoding = "GBK" to solve the GET request garbled problem.
2. response. setcontenttype ("text/XML; charset = GBK") is the Chinese encoding in the settings page.
The former sets dynamic text (parameters, databases), and the latter sets static text on the page.
Response. setcontenttype specifies the HTTP Response encoding and the encoding displayed by the browser.
Response. setcharacterencoding sets the HTTP Response encoding. If the encoding format is previously set using response. setcontenttype, the encoding format specified by response. setcharacterencoding overwrites the previous setting.
Same as response. setcontenttype, this method must be called inBefore getwriter is executed or before response is submitted
Supplement:
Problem 1: Passing parameters from the JSP page to displaying Chinese garbled characters in Servlet
Solution:
If the post method is used for submission, add the following code:
Request. setcharacterencoding ("GBK"); // ensure that the encoding is the first, and the encoding used for JSP pages (such as GBK and gb2312 ), this code is only valid for post submission.
Response. setcontenttype ("text/XML; charset = GBK") is set to Chinese encoding on the page
Note: The above two lines of code must be placed before printwriterout = response. getwriter ();
Get method submission
For example
String name = new string (request. getparameter ("name"). getbytes ("ISO-8859-1"), "GBK ");
Problem 2: Solve the Problem of garbled code submission in get mode:
Modify the Tomcat server. xml file and add the red code.
<Connector Port = "8080" protocol = "HTTP/1.1"
Connectiontimeout = "20000"
Redirectport = "8443"
Uriencoding = "GBK"/>
Note: The preceding encoding formats can be set as needed, as long as they are consistent.