Ajax (4): how to process a POST request form that contains Chinese Characters

Source: Internet
Author: User

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 ");}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.