JavaWeb-服务器输出字符数据到浏览器乱码-分析和解决(Java Web server output character data to browser garbled – Analysis and resolution)

服务器输出字符数据到浏览器

使用步骤

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //        1. 获取字符输出流对象
    PrintWriter pw = resp.getWriter();
    //        2. 输出数据到浏览器
    pw.write("<h1>hello response</h1>");
}

乱码原因分析

getWriter()默认获取流的编码为ISO-8859-1,则编码字符时的编码是ISO-8859-1。而客户端默认编码(windows平台)是GBK,解码采用的编码是GBK2313,编码不一致。

示意: 浏览器(GBK2312) <—–编码不一致——服务器(ISO-8859-1)

乱码问题解决

设置服务器响应的流采用的编码和客户端采用编码一致。

在使用流对象输出之前,设置编码

//        获取流对象之前,设置字符编码
resp.setCharacterEncoding("utf-8");

//        服务器告诉浏览器,发送消息采取的编码格式,建议浏览器使用该格式编码
resp.setHeader("content-type","text/html;charset=utf-8");
//        优化上述书写: 简单形式,设置编码
resp.setContentType("text/html;charset=utf-8");

说明: 表示设置流对象采用的编码为,同时建议浏览器采用编码也为。

resp.setContentType("text/html;charset=utf-8");
utf-8
utf-8

[视频]

————————

The server outputs character data to the browser

Use steps

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //        1. 获取字符输出流对象
    PrintWriter pw = resp.getWriter();
    //        2. 输出数据到浏览器
    pw.write("<h1>hello response</h1>");
}

Cause analysis of garbled code

Getwriter () gets the stream encoding as iso-8859-1 by default, so the encoding when encoding characters is iso-8859-1. The client’s default encoding (Windows platform) is GBK, and the encoding used for decoding is gbk2131, which is inconsistent.

Schematic: Browser (gbk2312) & lt—– Inconsistent encoding —– server (iso-8859-1)

Garbled code problem solving

Set the encoding of the server response stream to be consistent with that of the client.

Set encoding before using stream object output

//        获取流对象之前,设置字符编码
resp.setCharacterEncoding("utf-8");

//        服务器告诉浏览器,发送消息采取的编码格式,建议浏览器使用该格式编码
resp.setHeader("content-type","text/html;charset=utf-8");
//        优化上述书写: 简单形式,设置编码
resp.setContentType("text/html;charset=utf-8");

Note: indicates that the encoding used for setting the stream object is, and it is also recommended that the browser adopt the encoding of.

resp.setContentType("text/html;charset=utf-8");
utf-8
utf-8

[Video]