1

我希望我的自定义映射中的请求参数映射像

Map<String, String> reqMap =(HashMap<String, String>)request.getParameterMap();

上面的语句给了我以下异常

java.lang.ClassCastException: java.util.Collections$UnmodifiableMap

谁能指导我如何在自定义地图中获取所有请求参数?不想写 for 循环来一一获取参数,这会导致我出现性能问题。

4

4 回答 4

4

谨防将 Map 转换String, String为自 Java 6 以来 request.getParameterMap()返回类型的 Map 。 http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterMap()String, String[]

于 2014-02-06T10:03:03.750 回答
2
Map<String, String> reqMap = request.getParameterMap();
CustomMap<String, String> customMap = new CustomMap<String,String>();
customMap.putAll(reqMap);

当然,您可能需要在putAll()实现中遍历地图元素。否则是不可能的。

更新: 刚看到你的评论,泰语很容易,

Map<String, String> reqMap = request.getParameterMap();
Map<String, String> newMap= new HashMap<String,String>();
newMap.putAll(reqMap);

或者,您甚至可以将reqMap作为构造函数参数传递给new HashMap<String, String>(reqMap);

于 2012-06-27T14:53:04.087 回答
0

你可以试试这个方法:

public LinkedHashMap<String, String> returnMapOfRequest(HttpServletRequest request) 
    {
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        try 
        {
            Enumeration<String> parameterNames = request.getParameterNames();
            Enumeration<String> headerNames = request.getHeaderNames();
            while(headerNames.hasMoreElements()) 
            {
                String headerName = headerNames.nextElement();
                Enumeration<String> headers = request.getHeaders(headerName);
                while(headers.hasMoreElements())
                {
                    String headerValue = headers.nextElement();
                    map.put(headerName, headerValue);
                }
            }
            HttpSession session = request.getSession();
            Enumeration e = session.getAttributeNames();
            while(e.hasMoreElements())
            {
                String key = (String) e.nextElement();
                map.put(key, session.getAttribute(key));
            }
            while(parameterNames.hasMoreElements())
            {
                String paramName = parameterNames.nextElement();
                String[] paramValues = request.getParameterValues(paramName);
                for(int i = 0; i < paramValues.length; i++) 
                {
                    String paramValue = paramValues[i];
                    map.put(paramName, paramValue);
                }
            }
        }
        catch(Exception e)
        {
            logger.error("Exception in returnMapOfRequest  ::  ", e);
        }
        return map;
    }
于 2018-05-04T09:07:11.730 回答
-1

改变:

Map<String, String> reqMap =(HashMap<String, String>)request.getParameterMap();

到:

Map<String, String> reqMap =(Map<String, String>)request.getParameterMap();
于 2012-06-27T14:50:24.383 回答