About request parameter encoding processing

1. The occurrence of garbled request parameters

When the code used by the client is inconsistent with the code used by the web container, it may cause garbled characters

 

Example 1: The webpage encoding uses UTF-8, and sends a parameter request for the Chinese character "Qing" through Post. The web container handles encoding using ISO-8859-1.

Equivalent to what the browser does:

 

java.net.URLEncoder.encode("晴", "UTF-8");

"Qing" is encoded in UTF-8 as: %E6%99%B4

It is equivalent to what the web container does:

 

java.net.URLDecoder.decode("%E6%99%B4" , "ISO-8859-1");

 

Therefore, the request parameter garbled phenomenon will appear.

 

2. Post request parameter encoding processing

Before accepting any request parameters, execute the following statement (request instantiates an object for HttpServletRequest):

 

request.setCharacterEncoding("UTF-8");

 

Causes the container to use UTF-8 when accepting any request parameters. Can solve the garbled problem

 

3. Get request parameter encoding processing

request.setCharacterEncoding("UTF-8");

The above statement does not work for the problem of garbled Get request parameters.

why?

In the API, the method has the following description:

Overrides the name of the character encoding used in the body of this request

This method only takes effect on the character encoding in the request body. So in Get request, it does not solve the problem.

 

Still for example 1, as a Get request, the correct processing method is as follows:

 

String name = request.getParameter("name");
name = new String(name.getBytes("ISO-8859-1"),"UTF-8");

 

First , obtain the byte array of the string through getBytes() of String, and then reconstruct the correctly encoded string .

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325753267&siteId=291194637