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 你好,我是格格");
    }

}
相关推荐
浩浩测试一下5 小时前
Linux 底层知识点 1
linux·运维·服务器
Eloudy5 小时前
全文 - IMEX 第01节 -IMEX overview
运维·服务器·网络
Escalating_xu6 小时前
【Linux 网络编程】TCP 跨平台实战:用 Windows 客户端访问 Linux 服务器
linux·服务器·网络
发量惊人的中年网工6 小时前
分公司访问总部ERP慢怎么办?SD-WAN组网的排查与验收要点
服务器·开发语言·php
翼龙云_cloud7 小时前
亚马逊云服务器服务代理商:Bedrock 实践经验 Serverless 架构下的 AI 自动化落地
服务器·架构·serverless·云计算·aws
忆挽篱笙歌7 小时前
环境变量,本地变量
linux·运维·服务器
张宇Joaquin10 小时前
AMD uProf 工具采集微架构特征使用介绍
服务器
老李IT笔记10 小时前
连不上不一定是网不好:新系统不认的服务端配置卡在哪一档
运维·服务器·网络
刚入门的大一新生11 小时前
Linux-进程池
linux·运维·服务器
鱼很腾apoc11 小时前
【MySQL】第4期 用户管理与 C 语言连接编程详解
linux·服务器·c语言·mysql·connector/c