When a POST request is sent to the server and the form is input in Chinese, garbled characters often occur.
Solution: Add the following to the servlet that receives the request:Code:
Request. setcharacterencoding ("UTF-8 ");
For post requests sent using Ajax, the browser uses the UTF-8 for encoding. The role of this line of code is to programmatically specify the Tomcat server to be decoded in UTF-8, so that the encoding and decoding are consistent.
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"); 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 ");}}}