EN
Java - how to escape html special characters?
5
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");
Notes:
- more details in official documentation,
- see also full working example here.
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 = {
{ "&", "&" }, // keep this rule at first position
{ "<", "<" },
{ ">", ">" },
{ "\"", """ },
{ "'", "'" }
};
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:
<div class="item">Hi! How are you?</div>