Home  >  Article  >  Java  >  Garbled characters appear when url passes Chinese parameters in Java

Garbled characters appear when url passes Chinese parameters in Java

王林
王林Original
2019-12-05 14:05:032280browse

Garbled characters appear when url passes Chinese parameters in Java

Reason:

When HTTP request is transmitted, the url will be ISO-8859-1 encoding, after the server receives the byte stream, it will be decoded into a character stream by ISO-8859-1 encoding by default (causing Chinese garbled characters).

Method 1:

We need to put request.getParameter(" Parameter name")The obtained string is first encoded into a byte stream using ISO-8859-1, and then decoded into a character stream using utf-8.

String str = new String(request.getParameter("参数名").getBytes("iso-8859-1"), "utf-8");

This is to deal with the garbled problem through transcoding.

Online learning video tutorial sharing: java video

Method 2:

We can also set the URL encoding set (URIEncoding) through the Tomcat configuration file to set the encoding. This method is also once and for all.

Modify the server.xml file in the Tomcat/conf directory

<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8444" 
useBodyEncodingForURI="true" URIEncoding="UTF-8"/>

The focus is on the two attributes userBodyEncodingForURI and URIEncoding.

useBodyEncodingForURI parameter

indicates whether to use the request.setCharacterEncoding parameter to re-encode the data submitted by the URL and the data submitted by the GET method in the form. By default, this parameter is false.

URIEncoding parameter

Specifies the encoding for uniform recoding (decoding) of all GET request requests.

The difference between URIEncoding and useBodyEncodingForURI

URIEncoding is a unified recoding of all GET request data.

useBodyEncodingForURI re-encodes the data based on the request.setCharacterEncoding parameter of the page that responds to the request. Different pages can have different re-encoding codes.

Recommended related articles and tutorials: java entry program

The above is the detailed content of Garbled characters appear when url passes Chinese parameters in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn