获取单个请求参数
采用 request.getParameter(标签名称) 方法
获取多个请求参数
采用 request.getParameterValues() 方法,多用于获取复合标签 checkbox 中,返回 String[ ] 数组类型。
获取所有请求参数名称
采用 request.getParameterNames() 方法,返回 Enumeration<String> 类型。
Enumeration<String> parameterNames = request.getParameterNames();
System.out.println("表单所有参数名称:");
while (parameterNames.hasMoreElements()) {
System.out.println(parameterNames.nextElement());
}
获取所有请求参数
采用 request.getParameterMap() 方法,返回 Map<String, String[]> 类型,特别要注意该方法的遍历。
Map<String, String[]> parameterMap = request.getParameterMap();
System.out.println("表单所有参数:");
for (Entry<String, String[]> entry : parameterMap.entrySet()) {
System.out.println(entry.getKey());//获取键
System.out.println(Arrays.toString(entry.getValue()));//获取键值
}
上述内容综合代码
package com.RequestHttpServlet;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ThirdRequestServlet
*/
@WebServlet("/ThirdRequestServlet")
public class ThirdRequestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ThirdRequestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//获取单个请求参数
String userName = request.getParameter("username");
System.out.println("用户名是:"+userName);
//获取多个请求参数
String[] parameterValues = request.getParameterValues("userhobby");
System.out.println("用户爱好是:");
System.out.println(Arrays.toString(parameterValues));
//获取所有请求参数名称
Enumeration<String> parameterNames = request.getParameterNames();
System.out.println("表单所有参数名称:");
while (parameterNames.hasMoreElements()) {
System.out.println(parameterNames.nextElement());
}
//获取所有请求参数
Map<String, String[]> parameterMap = request.getParameterMap();
System.out.println("表单所有参数:");
for (Entry<String, String[]> entry : parameterMap.entrySet()) {
System.out.println(entry.getKey());//获取键
System.out.println(Arrays.toString(entry.getValue()));//获取键值
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/JWDemo/ThirdRequestServlet" method="get">
<input type="text" name="username" placeholder="请输入用户名">
<br>
<input type="radio" value="男" name="usersex">男
<input type="radio" value="女" name="usersex">女
<br>
<input type="checkbox" value="听音乐" name="userhobby">听音乐
<input type="checkbox" value="运动" name="userhobby">运动
<input type="checkbox" value="电子游戏" name="userhobby">电子游戏
<br>
<input type="submit" value="提交">
</form>
</body>
</html>