使用字符流转义Java库

时间:2011-08-09 20:11:43

标签: java security xss

是否有任何用于Java的HTML / JavaScript转义库具有字符流接口?

1 个答案:

答案 0 :(得分:1)

是。 Caja's Escaping class提供了将转义文本追加到Appendable以获取HTML,CSS,JavaScript,JavaScript正则表达式内容,JSON和XML的转发器。与WriterAppendable一样,StringBuilder实施StringBuffer

它还允许以一种模式转义JavaScript,允许它嵌入HTML <script>元素或XML CDATA部分,而无需通过编码尖括号进一步转义。

/**
 * Given a plain text string writes an unquoted javascript string literal.
 *
 * @param s the plain text string to escape.
 * @param asciiOnly Makes sure that only ASCII characters are written to out.
 *     This is a good idea if you don't have control over the charset that
 *     the javascript will be served with.
 * @param embeddable True to make sure that nothing is written to out that
 *     could interfere with embedding inside a script tag or CDATA section, or
 *     other tag that typically contains markup.
 *     This does not make it safe to embed in an HTML attribute without
 *     further escaping.
 * @param out written to.
 */
public static void escapeJsString(
    CharSequence s, boolean asciiOnly, boolean embeddable, Appendable out)
    throws IOException

并且有一个方便的方法,名称相同,但需要StringBuilder,并且不需要您处理IOException