request请求参数的通用方法
package cn.it.cast;
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;
import java.util.Map;
import java.util.Set;
@WebServlet("/RequestDemo6")
public class RequestDemo6 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//post请求参数
//根据参数获取参数值
String username = req.getParameter("username");
System.out.println("post");
System.out.println(username);
//根据参数名称获取参数值的数组
String[] hobbies = req.getParameterValues("hobby");
for(String hobby : hobbies){
System.out.println(hobby);
}
//请求所有参数的名称 Enumeration相当于iterator
Enumeration<String> parameterNames = req.getParameterNames();
while(parameterNames.hasMoreElements()){
String name = parameterNames.nextElement();
System.out.println(name);
String value = req.getParameter(name);
System.out.println(value);
System.out.println("-----------");
}
//获取所有参数的mao集合
Map<String,String[]> parameterMap = req.getParameterMap();
Set <String> keyset = parameterMap.keySet();
for (String name : keyset) {
//获取键获取值
String[] values = parameterMap.get(name);
System.out.println(name);
for (String value : values) {
System.out.println(value);
}
}
}
}