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?
習慣沉默
習慣沉默 2017-05-27 17:41:44
0
2
1098

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!

習慣沉默
習慣沉默

reply all(2)
淡淡烟草味

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.

给我你的怀抱

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

request.setCharacterEncoding(...)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template