Request请求参数中文乱码问题

发布时间 2023-04-20 20:33:51作者: YE-

Tomcat8以下的默认编码格式是ISO-8859-1 ,8版本以上Tomcat已经把默认编码格式改为UTF-8,此篇博客主要是解决Tomcat8以下版本的中文乱码问题处理。

一、Request请求参数中文乱码-POST解决方案

请求参数如果存在中文数据,则会乱码
解决方案:
POST:设置输入流的编码

req.setCharacterEncoding("UTF-8");
此方法只对Request请求POST解决方案有效。

        //1、解决乱码:POST.getReader()
        request.setCharacterEncoding("UTF-8");//设置字符输入流的编码
 
        //2、获取username
        String username = request.getParameter("username");
        System.out.println(username);

二、Request请求参数中文乱码-GET解决方案

URL编码
1、将字符串按照编码方式转为二进制
2、每个字节转为2个16进制并在前边加上%
Tomcat中文乱码产生原因:tomcat进行URL解码,tomcat8以前默认字符集ISO-8859-1
此方法可以同时解决POST和GET的中文乱码问题

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
 
/**
 * 中文乱码问题解决方案
 */
@WebServlet("/req4")
public class RequestDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
        //2、获取username
        String username = request.getParameter("username");
        System.out.println("解决乱码前"+username);
 
        //3、GET,获取参数的方式:getQueryString
        //3.1 先对乱码数据进行解码,转为字节数组
        byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
        //3.2 字节数组解码
        username = new String(bytes, StandardCharsets.UTF_8);
 
        System.out.println("解决乱码后" + username);
 
    }
 
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}