ClassCastException需要解析httpServeletRequest时

时间:2017-12-08 04:30:13

标签: java apache tomcat

我从tomcat运行我的代码但收到错误

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

下面的HttpUtils代码

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

但是像这样得到例外

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)

1 个答案:

答案 0 :(得分:1)

Map是一个接口,HashMap是一个具体的实现。 ParameterMap实施Map子类HashMap,因此无法投射HashMap。正确的做法通常是

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

program to the Map interface。但是,你可以做到

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

如果您需要 HashMap并拥有其他类型的Map,但这涉及到副本。