Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

Java - how to escape html special characters?

0 contributions
2 points

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");

Note: more details in official documentation.

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

1. Custom function example - based on replaceAll method

HTMLUtils.java file:

package com.dirask.examples;

import java.io.UnsupportedEncodingException;

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;
    }
}

Program.java file:

package com.dirask.examples;

import java.io.UnsupportedEncodingException;

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);

        System.out.println(escapedHtml);
    }
}

Output:

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

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey đź‘‹
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more