When a GET request is sent to the server and the form is entered with Chinese characters, garbled characters often occur.
SolutionTake two steps:
① When sending a GET request using Ajax, place the URL in the brackets of encodeuri.
② In the installation directory of the Tomcat server, find server. XML in the conf folder
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443"/>
With uriencoding = "UTF-8 ",
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/>
Explanation: the role of the first step is to forcibly specify the form of the Chinese data to the UTF-8 encoding, the role of the second step is to modify the Tomcat server default decoding mode for the UTF-8. In this way, the encoding and decoding methods are consistent, and garbled characters will not appear. Please note that you should not attempt to use the request. setcharacterencoding ("UTF-8") specifies the server's decoding method because this line of code only works for post requests and does not work for GET requests.
The test code is as follows:
Register. jsp:
<% @ Page contenttype = "text/html; charset = UTF-8 "pageencoding =" UTF-8 "%> <HTML>
Usernameservlet. Java:
Public class usernameservlet extends httpservlet {public void Service (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {// request. setcharacterencoding ("UTF-8"); // This line of code is only valid for post requests string uri = request. getrequesturi (); string Path = Uri. substring (URI. lastindexof ("/"), Uri. lastindexof (". "); response. setcontenttype ("text/html; charset = UTF-8"); printwriter PW = response. getwriter (); If (path. equals ("/valiusername") {string username = request. getparameter ("username"); system. out. println ("name:" + username); If (username. equals ("green") {PW. println ("username occupied");} else {PW. println ("user name can use") ;}} if (path. equals ("/register") {string username = request. getparameter ("username"); string Password = request. getparameter ("password"); response. sendredirect ("login. JSP ");}}}