DevToolsForYou

HTML Escape Tool in Java — Code Examples

HTML Escape Tool in JavaUse the online tool →

HTML escaping converts special characters like <, >, &, and " into their HTML entity equivalents (&lt;, &gt;, &amp;, &quot;) to prevent XSS attacks and ensure correct rendering. Here is how to escape and unescape HTML in each language.

Java's standard library lacks an HTML escaping utility. Use Apache Commons Text (StringEscapeUtils) or Spring's HtmlUtils.

Java (Apache Commons Text)
// Maven: org.apache.commons:commons-text:1.11.0
import org.apache.commons.text.StringEscapeUtils;

public class HtmlEscapeExample {
    public static void main(String[] args) {
        String raw = "<script>alert(\"xss\")</script> & \"quotes\"";

        // Escape HTML4 entities
        String escaped = StringEscapeUtils.escapeHtml4(raw);
        System.out.println(escaped);
        // &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; &amp; &quot;quotes&quot;

        // Unescape
        String unescaped = StringEscapeUtils.unescapeHtml4(escaped);
        System.out.println(unescaped);

        // Spring alternative (no extra dependency if already using Spring)
        // String escaped = org.springframework.web.util.HtmlUtils.htmlEscape(raw);
        // String unescaped = org.springframework.web.util.HtmlUtils.htmlUnescape(escaped);
    }
}
Notes & gotchas
  • escapeHtml4 handles HTML 4 named entities; it escapes <, >, &, ", and ' among others.
  • Spring's HtmlUtils.htmlEscape is a lightweight alternative if you are already using Spring.
  • In Thymeleaf / JSP templates, content is auto-escaped by default — use th:utext only for pre-escaped HTML.
Try it in your browser

Need to html escape/unescape without writing code? The HTML Escape Tool runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open HTML Escape/Unescape
HTML Escape Tool in other languages