获取请求参数通用方式:
不论是get还是post,都可以使用以下方法得到请求参数
1. string getParameter(String name) :根据参数名称获取参数值 username=zs&password=123
2. string[] getParameterValues (String name) :根据参数名称获取参数值的数组hobby=xx&hobby=game
一般用于复选框
3. Enumeration<String> getParameterNames() :获取所有请求的参数名称
4. Map<string, string[]> getParameterMap() :获取所有参数的map集合
string getParameter(String name) 根据参数名称获取参数值
regist2.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
</head>
<body>
<form action="/requestbody2" method="get">
<input type="text" name="username" placeholder="请输入用户名"><br>
<input type="password" name="password" placeholder="请输入密码"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
servlet:
@WebServlet("/requestbody2")
public class requestDemo extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//post 获取请求参数
//根据参数名称获取参数值
String username = request.getParameter("username");
System.out.println("post");
System.out.println(username);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get 获取请求参数
//根据参数名称获取参数值
// String username = request.getParameter("username");
// System.out.println("get");
// System.out.println(username);
this.doPost(request,response);//执行doPost代码逻辑,简化代码
}
}
string[] getParameterValues:用于复选框
html
<input type="checkbox" name="hobby" value="game">游戏
<input type="checkbox" name="hobby" value="study">学习
servlet:
//根据参数名称获取参数的数组
String[] hobbies = request.getParameterValues("hobby");
for (String hobby : hobbies) {
System.out.println(hobby);
}
Enumeration getParameterNames() :获取所有请求的参数名称
//获取所有请求的参数名称
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()){
String name = parameterNames.nextElement();
System.out.println(name);
String value = request.getParameter(name);
System.out.println(value);
System.out.println("---------------");
}
Map<string, string[]> getParameterMap() :获取所有参数的map集合
//获取所有参数的map集合
Map<String, String[]> parameterMap = request.getParameterMap();
//遍历
Set<String> keyset = parameterMap.keySet();
for (String name : keyset) {
//根据nanm获取值
String[] values = parameterMap.get(name);
System.out.println(name);
for (String value : values) {
System.out.println(value);
}
System.out.println("-----------------------");
}