Languages
[Edit]
EN

Java - how to escape html special characters?

5 points
Created by:
AnnLen
9180

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

Notes:

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;

 

Native Advertising
50 000 ad impressions - 449$
­čÜÇ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join