No modifications are allowed to a locked ParameterM&ParameterMap cannot be cast to java.util.HashMap

使用代理模式修改getParameterMap返回值时发现:报错
No modifications are allowed to a locked ParameterMap

查到以下

request.getParameterMap()返回值map是一个不可更改的map?
https://blog.csdn.net/Luminescende/article/details/81140554

测试如下可以
Map map1= (Map) method.invoke(req, args);
Map map = new HashMap(map1);

完整代码如下

  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        ServletRequest proxy_req = (ServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
             
                //判断是否是调用getParameter
                if (method.getName().equals("getParameterMap")) {
                    //是要增强返回值
                    // Map map =(Map) method.invoke(req, args);原来方式
                    //更改之后
                    Map<String, String[]> map = new HashMap<String,String[]>((Map<String,String[]>) method.invoke(req, args));
                    for (String key : map.keySet()) {
                        String[] values = map.get(key);
                        //list是敏感词集合
                        for (String str : list) {
                            if (values[0].contains(str)) {
                                values[0] = values[0].replaceAll(str, "***");
                            }
                        }
                        map.put(key,values);
                    }

                    return map;
                }
                return method.invoke(req,args);
            }
        });
        chain.doFilter(proxy_req, resp);
    }
    ```

你可能感兴趣的:(学习笔记)