Tomcat server request encoding
By default in Tomcat, data is transmitted in ISO-8859-1 encoding during the transmission between the server and the browser. If the transmission is Chinese, garbled characters will appear. In order to solve the problem of obtaining the Chinese parameters of the request, we can first decode the data into binary with ISO-8859-1 encoding, and then convert it into UTF-8. The code is as follows:
//byte[] bytes = account.getBytes("ISO-8859-1");
//account = new String(bytes, "UTF-8");
The above form can solve our problem, but it is a waste of time to write this kind of code every time. The following introduces other solutions
GET method
You can add URIEncoding configuration in tomcat's conf/server.xml (but in general, we do not require GET to pass Chinese parameters):
<Connector port="8081" protocol="HTTP/1.1"
connectionTimeout="20000"
URIEncoding="UTF-8"
redirectPort="8443" />
POST method
For POST requests, we can add the code setCharacterEncoding() before getting the parameters:
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
//记住设置编码的代码必须在获取参数内容代码之前
String account = req.getParameter("account");
}
Tomcat server response encoding
As mentioned above, if the request code for obtaining the browser is in Chinese, there will be garbled characters. Now, when Chinese is sent to the browser, garbled characters will also appear. code show as below:
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getOutputStream().write("Hello world".getBytes());
resp.getOutputStream().write("深度学习".getBytes());
}
Solution 1:
resp.setCharacterEncoding("UTF-8");
resp.getOutputStream().write("Hello world<br />".getBytes());
resp.getOutputStream().write("深度学习".getBytes());
Solution 2:
resp.setContentType("text/html;charset=utf-8");
resp.getOutputStream().write("Hello world<br />".getBytes());
resp.getOutputStream().write("深度学习".getBytes());