gpt4 book ai didi

java - 需要解析httpServletRequest时出现ClassCastException

转载 作者:行者123 更新时间:2023-11-28 22:48:40 25 4
gpt4 key购买 nike

我从 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)

最佳答案

Map是接口(interface),HashMap是具体实现。 ParameterMap实现了 Map没有子类 HashMap 所以它不能castHashMap。正确的做法通常是

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

program to the Map interface .但是,您可以这样做

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

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

关于java - 需要解析httpServletRequest时出现ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47707738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com