views:

1622

answers:

3

Is there a recommended way to escape <, >, " and & characters when outputting HTML in plain Java code? (Other than manually doing the following, that is).

String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = source.replace("<", "&lt;").replace("&", "&amp;"); // ...
+15  A: 

StringEscapeUtils from Apache Commons Lang:

import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
// ...
String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = escapeHtml(source);
dfa
+9  A: 

An alternative to Apache Commons: Use Spring's HtmlUtils.htmlEscape(String input) method.

Adamski
+1  A: 

For some purposes:
HtmlUtils.htmlEscapeDecimal("&") gives &#38;
HtmlUtils.htmlEscape("&") gives &amp;

AUU