Recommended method for escaping HTML in Java

前端 未结 11 1100
南旧
南旧 2020-11-22 04:30

Is there a recommended way to escape <, >, \" and & characters when outputting HTML in plain Java code? (Other

11条回答
  •  死守一世寂寞
    2020-11-22 04:58

    Nice short method:

    public static String escapeHTML(String s) {
        StringBuilder out = new StringBuilder(Math.max(16, s.length()));
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c > 127 || c == '"' || c == '\'' || c == '<' || c == '>' || c == '&') {
                out.append("&#");
                out.append((int) c);
                out.append(';');
            } else {
                out.append(c);
            }
        }
        return out.toString();
    }
    

    Based on https://stackoverflow.com/a/8838023/1199155 (the amp is missing there). The four characters checked in the if clause are the only ones below 128, according to http://www.w3.org/TR/html4/sgml/entities.html

提交回复
热议问题