Request和Response学习笔记4

Request 获取请求参数,中文乱码问题

实例引入:

  1. 创建一个html文件:garbled.html

    复制
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>中文乱码问题</title>
    </head>
    <body>
    <form action="/RequestResponseCharset_war_exploded/demo01" method="get">
    <label><input type="text" name="username" placeholder="请输入用户名"></label><br>
    <label><input type="password" name="password" placeholder="请输入密码"></label><br>
    <input type="submit" value="get提交">
    </form>
    <br>
    <form action="/RequestResponseCharset_war_exploded/demo01" method="post">
    <label><input type="text" name="username" placeholder="请输入用户名"></label><br>
    <label><input type="password" name="password" placeholder="请输入密码"></label><br>
    <input type="submit" value="post提交">
    </form>
    </body>
    </html>
  2. 创建一个类:CharsetGarbled.java

    复制
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    /**
    * @Author: YiHua Lee
    * @Version: 1.8.0_201 Java SE 8
    * @Application: IntelliJ IDEA
    * @CreateTime: 2020/5/18 22:10
    * @Description:
    */
    @WebServlet("/demo01")
    public class CharsetGarbled extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    // 获取请求参数
    String username = req.getParameter("username");
    System.out.println(username);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    this.doGet(req, resp);
    }
    }
  3. 启动服务器,浏览器访问:http://localhost:8080/RequestResponseCharset_war_exploded/garbled.html

    20200518230548
  4. 解决中文乱码问题

    只需要改动doGet()方法即可:

    复制
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    // 设置流的编码
    req.setCharacterEncoding("utf-8");
    // 获取请求参数
    String username = req.getParameter("username");
    System.out.println(username);
    }
  5. 重启服务器,再次访问:http://localhost:8080/RequestResponseCharset_war_exploded/garbled.html

    并用post提交,控制台输出:

    复制
    彩虹

    浏览器页面跳转到:http://localhost:8080/RequestResponseCharset_war_exploded/demo01

参考文献

  1. 解决Tomcat请求中文乱码的问题
  2. 更改Tomcat字符编码设置及解决post请求中文字符乱码
  3. Tomcat Http请求中文乱码
posted @   LeeHua  阅读(99)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示

目录导航