JavaWeb--POST/GET请求参数乱码问题

发布时间 2023-11-16 16:09:51作者: na2co3-

只要添加编码方式就可以解决POST中的乱码问题

 //1、解决POST乱码问题
        request.setCharacterEncoding("UTF-8");


        //2、获取username
        String username = request.getParameter("username");
        System.out.println(username);

使用GET却不能使用这种方法解决

 String username = request.getParameter("username");
        //System.out.println(username);
        System.out.println("解决乱码问题前"+username);
        //3、GET,获取参数的方式:getQueryString
        //乱码原因:tomcat对url解码时使用的是默认字符集ISO-8859-1
        //3.1 先对乱码数据进行编码:转为字节数组
        byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
        //3.2字节数组解码
        username = new String(bytes,StandardCharsets.UTF_8);
        System.out.println("解决乱码问题后"+username);

POST和GET方式都可以用这种方式提交