简体   繁体   English

需要解析httpServeletRequest时的ClassCastException

[英]ClassCastException when need to parse httpServeletRequest

I run my code from tomcat but getting error 我从tomcat运行我的代码,但出现错误

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

HttpUtils code below HttpUtils代码如下

    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. Map是接口, HashMap是具体实现。 ParameterMap implements Map but does not sub-class HashMap so it cannot be cast to a HashMap . ParameterMap实现了Map ,但子类HashMap所以它不能被转换为一个HashMap The proper thing to do is usually 通常正确的做法是

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

and program to the Map interface . 编程到Map接口 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. 如果您需要 HashMap并拥有其他种类的Map ,但其中涉及一个副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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