Home  >  Q&A  >  body text

There is a little doubt about how the servlet filter in Java solves the problem of Chinese garbled characters. Is it necessary to use entrySet traversal here?

The filter code for solving the problem of Chinese garbled characters found on the Internet has a paragraph similar to the following:

Map<String,String[]> map = request.getParameterMap();//获取有乱码的map  
if(isNotEncode){//只能在第一次解决乱码  
    for(Map.Entry<String, String[]> entry : map.entrySet()){//遍历map,解决所有值的乱码  
        String [] vs = entry.getValue();  
        for(int i=0;i<vs.length;i++){  
            vs[i] = new String(vs[i].getBytes("iso8859-1"),encode);  
        }  
    }  
    isNotEncode = false;//设置为false,第二次就不会再进这个代码块了  
}  
return map;  

Here we only modify the value set in the map. This value set is a collection of String arrays. In fact, we only modify the elements in the String array. I feel that there is no need to take out the entrySet and traverse it. You can achieve the same effect by just taking out the Values ​​and traversing it. I practiced it myself and confirmed my conjecture. But almost all the information I see on the Internet traverses entrySet. Why is this? Are there any loopholes in just traversing the value set Values? I hope the experts can clear up the confusion!

習慣沉默習慣沉默2702 days ago1036

reply all(2)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-27 17:43:44

    This is what you mean:

    for (String[] values : map.values()) {
        for (int i = 0; i < values.length; i ++) {
            values[i] = new String(values[i].getBytes(StandardCharsets.ISO_8859_1, encode));
        }
    }
    

    I don’t think there’s anything wrong with it.

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-27 17:43:44

    It’s completely unnecessary, see the source code of Tomcat’s SetCharacterEncodingFilter

    request.setCharacterEncoding(...)

    reply
    0
  • Cancelreply