[Ljava.lang.String; cannot be cast to java.lang.String

xiaoxiao2021-02-28  68

试图通过resquest对象获取前端请求键值对,即request.getParamMap()

本来代码如下:

Map<String,String> map=request.getParamMap();

Map<String,String> map= request.getParameterMap(); Set<String> set=map.keySet(); Iterator<String> it=set.iterator(); while(it.hasNext()) { String next= it.next(); System.out.println("key:"+next+"->value:"+map.get(next)); } 然而报错,这是为什么呢?

看源码,map来自request对象,查看源码即可知道:

/** Returns a java.util.Map of the parameters of this request. * Request parameters * are extra information sent with the request. For HTTP servlets, * parameters are contained in the query string or posted form data. * * @return an immutable java.util.Map containing parameter names as * keys and parameter values as map values. The keys in the parameter * map are of type String. The values in the parameter map are of type * String array. * */

返回一个request的请求参数map

重点看划线部分的of type String  ,of type String array

就是说key是String

value是String[]

解决后代码:

Map<String,String[]> map= request.getParameterMap(); Set<String> set=map.keySet(); Iterator<String> it=set.iterator(); while(it.hasNext()) { String next= it.next(); System.out.println("key:"+next+"->"); for(String s:map.get(next)) { System.out.println("value:"+s); }

}

运行结果就正常了,

这告诉我们,多看源码,抠单词

转载请注明原文地址: https://www.6miu.com/read-2612713.html

最新回复(0)