Java escape HTML

后端 未结 6 999
故里飘歌
故里飘歌 2020-12-03 06:34

currently I use org.apache.commons.lang.StringEscapeUtils escapeHtml() to escape unwanted HTML tags in my Strings but then I realized it escapes characters with

相关标签:
6条回答
  • 2020-12-03 07:08

    I know is too late to adding my comment, but perhaps the following code will be helpful:

    public static String escapeHtml(String string) {
        StringBuilder escapedTxt = new StringBuilder();
        for (int i = 0; i < string.length(); i++) {
            char tmp = string.charAt(i);
            switch (tmp) {
            case '<':
                escapedTxt.append("&lt;");
                break;
            case '>':
                escapedTxt.append("&gt;");
                break;
            case '&':
                escapedTxt.append("&amp;");
                break;
            case '"':
                escapedTxt.append("&quot;");
                break;
            case '\'':
                escapedTxt.append("&#x27;");
                break;
            case '/':
                escapedTxt.append("&#x2F;");
                break;
            default:
                escapedTxt.append(tmp);
            }
        }
        return escapedTxt.toString();
    }
    

    enjoy!

    0 讨论(0)
  • 2020-12-03 07:12

    If you're using Wicket, use:

    import org.apache.wicket.util.string.Strings;
    ...
    CharSequence cs = Strings.escapeMarkup(src);
    String str =      Strings.escapeMarkup(src).toString();
    
    0 讨论(0)
  • 2020-12-03 07:14

    If it's for Android, use TextUtils.htmlEncode(String) instead.

    0 讨论(0)
  • 2020-12-03 07:16

    Here's a version that replaces the six significant characters as recommended by OWASP. This is suitable for HTML content elements like <textarea>...</textarea>, but not HTML attributes like <input value="..."> because the latter are often left unquoted.

    StringUtils.replaceEach(text,
            new String[]{"&", "<", ">", "\"", "'", "/"},
            new String[]{"&amp;", "&lt;", "&gt;", "&quot;", "&#x27;", "&#x2F;"});
    
    0 讨论(0)
  • 2020-12-03 07:18
    StringUtils.replaceEach(str, new String[]{"&", "\"", "<", ">"}, new String[]{"&amp;", "&quot;", "&lt;", "&gt;"})
    
    0 讨论(0)
  • 2020-12-03 07:21

    This looks very good to me:

    org/apache/commons/lang3/StringEscapeUtils.html#escapeXml(java.lang.String)

    By asking XML, you will get XHTML, which is good HTML.

    0 讨论(0)
提交回复
热议问题