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进程(三)
linux·运维·服务器·环境变量·命令行参数
minji...9 小时前
Linux 基础IO(一) (C语言文件接口、系统调用文件调用接口open,write,close、文件fd)
linux·运维·服务器·网络·数据结构·c++
码龄3年 审核中9 小时前
Linux record 04
linux·运维·服务器
RisunJan9 小时前
Linux命令-ftptop命令(实时监控 ProFTPD 服务器连接状态)
linux·运维·服务器
虾..9 小时前
Linux 文件描述符,重定向及缓冲区理解
linux·运维·服务器
真正的醒悟9 小时前
202503-经验之道
服务器·网络·php
db_cy_206210 小时前
Git对服务器配置文件进行版本控制
运维·服务器·git
qq_2516161910 小时前
ubuntu nginx文件服务器
linux·服务器·网络
渴望成为python大神的前端小菜鸟10 小时前
浏览器及其他 面试题
前端·javascript·ajax·面试题·浏览器
晚风吹长发10 小时前
初步了解Linux中文件描述符-fd
linux·运维·服务器·c++·开发·文件