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 @ 2021-03-03 22:42  LeeHua  阅读(98)  评论(0编辑  收藏  举报