request.getParameterMap()的返回类型是Map类型的对象,也就是符合key-value的对应关系,
但这里要注意的是,value的类型是String[],而不是String.
得到jsp页面提交的参数很容易,但通过它可以将request中的参数和值变成一个map,以下是将得到的参数和值打印出来,形成的map结构:map(key,value[]),即:key是String型,value是String型数组。
例如:request中的参数t1=1&t1=2&t2=3
形成的map结构:
key=t1;value[0]=1,value[1]=2
key=t2;value[0]=3
如果直接用map.get("t1"),得到的将是:Ljava.lang.String; value只所以是数组形式,就是防止参数名有相同的情况。
如果直接用map.get("t1"),得到的将是:Ljava.lang.String; value只所以是数组形式,就是防止参数名有相同的情况。
将request.getParameterMap()转换成可操作的普通的map
public static Map getParameterMap(HttpServletRequest request) {
Map properties = request.getParameterMap();
// 返回值Map
Map returnMap = new HashMap();
Iterator entries = properties.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
while (entries.hasNext()) {
entry = (Map.Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
value = values[i] + ",";
}
value = value.substring(0, value.length()-1);
}else{
value = valueObj.toString();
}
returnMap.put(name, value);
}
return returnMap;
}
Map properties = request.getParameterMap();
// 返回值Map
Map returnMap = new HashMap();
Iterator entries = properties.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
while (entries.hasNext()) {
entry = (Map.Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
value = values[i] + ",";
}
value = value.substring(0, value.length()-1);
}else{
value = valueObj.toString();
}
returnMap.put(name, value);
}
return returnMap;
}
还有一种方法也可以实现:
Map maps=request.getParameterMap();
Set sets=maps.keySet();
Iterator it=sets.iterator();
while(it.hasNext()){
String strName=it.next().toString();
out.print(strName);
out.print("=========>>>>");
Object objs=maps.get(strName);
if(objs instanceof String[]){
String[] strs=(String[])objs;
out.print(Arrays.toString(strs));
}
out.print("<br>");
}
Set sets=maps.keySet();
Iterator it=sets.iterator();
while(it.hasNext()){
String strName=it.next().toString();
out.print(strName);
out.print("=========>>>>");
Object objs=maps.get(strName);
if(objs instanceof String[]){
String[] strs=(String[])objs;
out.print(Arrays.toString(strs));
}
out.print("<br>");
}
getParameterNames()是获取request请求的参数名称:
Enumeration enums=request.getParameterNames();
while(enums.hasMoreElements()){
out.print(enums.nextElement());
out.print("<br>");
}
while(enums.hasMoreElements()){
out.print(enums.nextElement());
out.print("<br>");
}