获取用户的用户名

一、方法

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

二、实现

  1. public class RequestTestServlet extends HttpServlet {
  2. @Override
  3. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  4. throws ServletException, IOException {
  5. //设置请求体的字符集
  6. //以免Tomcat9级以下版本出现乱码
  7. request.setCharacterEncoding("UTF-8");
  8. //这是Post请求
  9. String username = request.getParameter("username");
  10. //输出这个用户提交的用户名
  11. System.out.println(username);
  12. }
  13. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  5. version="4.0">
  6. <servlet>
  7. <servlet-name>RequestTestServlet</servlet-name>
  8. <servlet-class>servlet.RequestTestServlet</servlet-class>
  9. </servlet>
  10. <servlet-mapping>
  11. <servlet-name>RequestTestServlet</servlet-name>
  12. <url-pattern>/testrequest</url-pattern>
  13. </servlet-mapping>
  14. </web-app>

5、获取用户的用户名 - 图1

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

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

3.1 解决

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