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

三、解决请求体的乱码问题
- ✅Tomcat9版本以下,若用户输入中文表单,通过前端输入到后端的数据则会显示乱码
3.1 解决
//设置请求体的字符集
//以免Tomcat9级以下版本出现乱码
request.setCharacterEncoding("UTF-8");