TomCat乱码问题

TomCat控制台乱码问题

乱码问题解决:

响应乱码问题

向客户端响应数据:

java 复制代码
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 响应头,告诉浏览器以指定的字符集解析响应体 ( 推荐 )

java 复制代码
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 你好,我是格格");
    }

}
相关推荐
勤奋的凯尔森同学4 小时前
webmin配置终端显示样式,模仿UbuntuDesktop终端
linux·运维·服务器·ubuntu·webmin
丁卯4045 小时前
Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
服务器·后端·golang
chengooooooo5 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
人间打气筒(Ada)6 小时前
MySQL主从架构
服务器·数据库·mysql
落笔画忧愁e7 小时前
FastGPT快速将消息发送至飞书
服务器·数据库·飞书
小冷爱学习!7 小时前
华为动态路由-OSPF-完全末梢区域
服务器·网络·华为
落幕8 小时前
C语言-进程
linux·运维·服务器
林的快手10 小时前
CSS列表属性
前端·javascript·css·ajax·firefox·html5·safari
liaojuajun11 小时前
axios
ajax
xmweisi11 小时前
【华为】报文统计的技术NetStream
运维·服务器·网络·华为认证