Home  >  Article  >  Java  >  Several ways to deal with garbled characters in java

Several ways to deal with garbled characters in java

尚
Original
2019-12-16 10:44:473129browse

Several ways to deal with garbled characters in java

Solution 1 (If there are many garbled parameters, it will be less efficient)

The default encoding of the browser is ISO-8859-1, and the back-end Servlet receives the request parameters. Decode according to ISO-8859-1 to obtain a binary stream, and then encode it with UTF-8.

Sample code:        

// 获得请求参数
String queryString = request.getQueryString();
// 按照ISO-8859-1方式解码
byte[] bytes = queryString.getBytes("ISO-8859-1");
// 按照UTF-8编码
String param = new String(bytes,"UTF-8");

Solution 2 (this method only supports get request)

Modify the server (tomcat) configuration: in server.xml, the default is ISO-8859-1 (not shown), we can add UTF-8

Several ways to deal with garbled characters in java

Solution 3 (this method only supports post request)

Set the request parameter encoding directly in the servlet--Recommendation

//设置请求参数编码 
request.setCharacterEncoding("UTF-8");

Response garbled code--Response

// 设置MIME类型
response.setContentType("text/html");
// 设置编码
response.setCharacterEncoding("UTF-8");
//设置编码(简写)
response.setContentType("text/html;charset=utf-8");

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of Several ways to deal with garbled characters 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