Servlet 之 request获取请求参数的通用方式
获取请求参数的通用方式
根据参数获取参数值:
String name = request.getParameter(“name”);
根据参数获取参数值的数组:
String[] hobbies = request.getParameterValues(“hobby”);
获取所有请求的参数名称:
Enumeration parameterNames = request.getParameterNames();
获取所有参数的map集合
Map<String,String[]> getParameterMap();
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;
import java.util.Enumeration;
@WebServlet("/RegisterDemo")
public class RegisterDemo extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//通用方法
//根据参数获取参数值
String name = request.getParameter("name");
//根据参数获取参数值的数组
String[] hobbies = request.getParameterValues("hobby");
for (String hobby : hobbies) {
System.out.println(hobby);
}
//获取所有请求的参数名称
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()){
String name1 = parameterNames.nextElement();
System.out.print(name1);
String value = request.getParameter(name1);
System.out.println(value);
//获取所有参数的map集合
Map<String, String[]> parameterMap = request.getParameterMap();
//遍历
Set<String> keyset = parameterMap.keySet();
for (String key : keyset) {
//获取集合中的键和值
String[] values = parameterMap.get(key);
System.out.println(key);
for (String value : values) {
System.out.println(value);
}
System.out.println("-------");
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
相应的html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
<form action="/RegisterDemo" method="post">
<input type="text" placeholder="请输入用户名" name="username"> <br>
<input type="text" placeholder="请输入密码" name="password"> <br>
<input type="checkbox" name="hobby" value="game"> 游戏
<input type="checkbox" name="hobby" value="study"> 学习
<input type="submit" value="注册">
</form>
</head>
<body>
</body>
</html>
英雄,愿你有一份不悔的爱情