Recently, I have been doing servlet-related things. garbled characters are often annoying. The method for handling garbled characters is sometimes effective and sometimes ineffective. Let's take a look at it today, in case of such problems in the future.
Generally, the following methods are used to handle Garbled text:
Request. setcharacterencoding ("GBK ")
However, this method only works for the form submitted by the POST method. This is the reason why the previously mentioned method sometimes works and sometimes does not work.
Online data shows that Tomcat uses different encoding methods to process the information submitted by get and post methods since tomcat5.x. Tomcat still uses request for post requests. the encoding set by the setcharacterencoding method, uses the default iso-8859-1 encoding if not set. However, GET requests are different. Tomcat does not consider request for GET requests. the setcharacterencoding method sets the encoding, and will always use the iso-8859-1 encoding, so Tomcat will use the iso-8859-1 to convert the committed bytes into strings.
In view of this, three solutions are provided:
1. Change the GET request to the POST request. Then you can use the request. setcharacterencoding method to set the encoding and use the request. getparameter method to directly obtain the Chinese request parameters. This method is simple and clear.
2. Do not change the GET request. Use the following code in the servlet to obtain the Chinese request parameters.
String name = new string (request. getparameter ("name"). getbytes ("ISO-8859-1"), "GBK ");
3. For the get method, you can also modify the tomcat configuration.
The method is as follows:
Add uriencoding = "GBK" or a UTF-8 to the <connector/> label in CONF/server. xml. For example:
<Connector Port = "8080" protocol = "HTTP/1.1" redirectport = "8443" uriencoding = "GBK"/>
For the form submitted by the POST method, method 2 is still valid. I suggest using method 2 because the code of method 2 uses the Java encoding capability, the setcharacterencoding method is supported by Web servers. Not all Web servers support this method.
Garbled characters generated by Tomcat when processing get and post requests