Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the recommended way to escape HTML symbols in plain Java?

Is there a recommended way to escape <, >, " and & characters when outputting HTML in plain Java code? (Other than manually doing the following, that is).

String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML"; String escaped = source.replace("<", "&lt;").replace("&", "&amp;"); // ... 
like image 951
Ben Lings Avatar asked Aug 12 '09 09:08

Ben Lings


People also ask

How do you escape a HTML character in Java?

In Java, we can use Apache commons-text , StringEscapeUtils. escapeHtml4(str) to escape HTML characters. In the old days, we usually use the Apache commons-lang3 , StringEscapeUtils class to escape HTML, but this class is deprecated as of 3.6.

What is escapes in HTML?

Escaping in HTML means, that you are replacing some special characters with others. In HTML it means usally, you replace e. e.g < or > or " or & . These characters have special meanings in HTML. Imagine, you write <b>hello, world</b> And the text will appear as hello, world.


1 Answers

StringEscapeUtils from Apache Commons Lang:

import static org.apache.commons.lang.StringEscapeUtils.escapeHtml; // ... String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML"; String escaped = escapeHtml(source); 

For version 3:

import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4; // ... String escaped = escapeHtml4(source); 
like image 80
dfa Avatar answered Sep 24 '22 08:09

dfa