Escaping libraries for Java using character streams
Are there 开发者_开发技巧any HTML/JavaScript escaping libraries for Java that have a character stream interface?
Yes. Caja's Escaping
class provides escapers that append the escaped text to an Appendable
for HTML, CSS, JavaScript, JavaScript regex content, JSON, and XML. Java Writer
s implement Appendable
as do StringBuilder
and StringBuffer
.
It also allows escaping JavaScript in a mode that allows it to be embedded in an HTML <script>
element or XML CDATA section without further escaping by encoding angle brackets.
/**
* 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
and there's a convenient method with the same name but that takes a StringBuilder
and does not require you to handle IOException
.
精彩评论