简体   繁体   中英

ClassCastException when need to parse httpServeletRequest

I run my code from tomcat but getting error

HashMap<String, Object> params;
params = (HashMap) HttpUtils.getParamsFromRequest(request);

HttpUtils code below

    public static Map<String, ? extends Object> getParamsFromRequest(HttpServletRequest httpServletRequest) {
    return httpServletRequest.getParameterMap();
}

but getting exception like this

java.lang.ClassCastException: org.apache.catalina.util.ParameterMap cannot be cast to java.util.HashMap
at se.mindspot.tender.backend.servlet.service.file.FileServiceServlet.doGet(FileServiceServlet.java:47)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Map is an interface, HashMap is a concrete implementation. ParameterMap implements Map but does not sub-class HashMap so it cannot be cast to a HashMap . The proper thing to do is usually

Map<String, Object> params;
params = HttpUtils.getParamsFromRequest(request);

and program to the Map interface . However, you can do

params = new HashMap<>(HttpUtils.getParamsFromRequest(request));

if you need a HashMap and have some other kind of Map , but that involves a copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM