Solving the garbled problem in the process of request and response in Servlet

The solution to the garbled problem in Servlet

1. Garbled code in POST request:

    // 必须要在获取请求参数之前调用才有效
    req.setCharacterEncoding("UTF-8");

2. Garbled code in the Get request:

After obtaining the request parameters, you can first encode the tomcat side (that is, encode with iso8859-1 first), and then decode with utf-8.

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

3. Solving the garbled problem in the response:

Option One:

Set the character set of the server and the browser to the UTF-8 character set uniformly. The location is not required.

// 设置服务器字符集为 UTF-8
resp.setCharacterEncoding("UTF-8");
// 通过响应头,设置浏览器也使用 UTF-8 字符集
resp.setHeader("Content-Type", "text/html; charset=UTF-8");
Option two (recommended for wall cracks):

The code is more concise, but this setting must be called before the stream object is obtained to take effect.

// 它会同时设置服务器和客户端都使用UTF-8字符集,还设置了响应头
resp.setContentType("text/html; Charset=UTF-8");
//一定要记住在获取流对象之前调用才会有效。

Guess you like

Origin blog.csdn.net/qq_45796486/article/details/114222446