TomCat乱码问题
TomCat控制台乱码问题
乱码问题解决:
响应乱码问题
向客户端响应数据:
package Servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/servlet4_4")
public class servlet4_4 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("hello 你好,我是格格");
}
}
方式1
:后端通过设置响应体的字符集和浏览器解析响应体的默认字符集一致
(
不推荐
)
方式二:通过设置
Content-Type
响应头,告诉浏览器以指定的字符集解析响应体
(
推荐
)
package Servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/servlet4_4")
public class servlet4_4 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setCharacterEncoding("GBK"); 后端适应前端,不推荐,前端解析字符集是不确定的
// 告诉客户端使用指定字符集进行解码 通过设置Content-Type响应头
// 需要注意的是要明确响应体的编码,然后在设置Content -type
// 没置响应体使用UTF-8编码(可以不写)
resp.setCharacterEncoding("UTF-8");
// 没置Content-Type响应头,告诉客户端用UTF-8解码
resp.setContentType("text/html;charset = UTF-8");
resp.getWriter().write("hello 你好,我是格格");
}
}