1、方法

  • String username = request.getParameter("username");

    2、实现

    ```java package servlet;

import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException; import java.io.PrintWriter; import java.net.HttpCookie;

/**

  • @Author: 小雷学长
  • @Date: 2022/3/20 - 17:22
  • @Version: 1.8 */ public class RequestTestServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response)

    1. throws ServletException, IOException {
    2. //设置请求体的字符集
    3. //以免Tomcat9级以下版本出现乱码
    4. request.setCharacterEncoding("UTF-8");
  1. //这是Post请求
  2. String username = request.getParameter("username");
  3. //输出这个用户提交的用户名
  4. System.out.println(username);
  5. }

}

  1. ```xml
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  6. version="4.0">
  7. <servlet>
  8. <servlet-name>RequestTestServlet</servlet-name>
  9. <servlet-class>servlet.RequestTestServlet</servlet-class>
  10. </servlet>
  11. <servlet-mapping>
  12. <servlet-name>RequestTestServlet</servlet-name>
  13. <url-pattern>/testrequest</url-pattern>
  14. </servlet-mapping>
  15. </web-app>

image.png

3、解决请求体的乱码问题

  • [x] Tomcat9版本以下,若用户输入中文表单,通过前端输入到后端的数据则会显示乱码

    3.1 解决

    1. //设置请求体的字符集
    2. //以免Tomcat9级以下版本出现乱码
    3. request.setCharacterEncoding("UTF-8");
  • [x] Tomcat10版本及以后不需要考虑乱码问题题