Java - how to escape html special characters?

5 points
Created by:

Using Java it is possible to escapse HTML secial characters in following ways.

When we use Spring Framework we can use:

//import org.springframework.web.util.HtmlUtils

String html = "<p>Some text here...</p>";

String escaped1Html = HtmlUtils.htmlEscape(html); // "ISO-8859-1" by default
String escaped2Html = HtmlUtils.htmlEscape(html, "UTF-8");


In other case we can try to use some alternative custom version:

1. Custom function example - based on replaceAll method file:

package com.dirask.examples;


public class HTMLUtils {
    private static final String[][] CHARACTERS = {
		{  "&", "&amp;"  }, // keep this rule at first position
		{  "<", "&lt;"   },
		{  ">", "&gt;"   },
		{ "\"", "&quot;" },
		{  "'", "&#039;" }

    public static String escape(String html) throws UnsupportedEncodingException {
        String result = html;

        for(String[] entry : CHARACTERS) {
            result = result.replaceAll(entry[0], entry[1]);

        return result;
} file:

package com.dirask.examples;


public class Program {

    public static void main(String[] args) throws UnsupportedEncodingException {

        String html = "<div class=\"item\">Hi! How are you?</div>";
        String escapedHtml = HTMLUtils.escape(html);



&lt;div class=&quot;item&quot;&gt;Hi! How are you?&lt;/div&gt;


Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍