Pages Navigation Menu

Coding is much easier than you think

How To Escape Special Characters of JSP using Java code?

How To Escape Special Characters of JSP using Java code?

Often times, we encountered some special characters or arbitrary text placed in an HTML tag that resulting an invalid HTML output. The special characters often needs to be altered or escape to ensure the resulting HTML is still valid.

Special characters as follow
1) <
2) >
3) \
4) &

StringEscapeUtils which included in commons-lang.jar library, is used to escape special characters in Java.

Here is the source code to demonstrate how to escape special characters with StringEscapeUtils class.


import org.apache.commons.lang.StringEscapeUtils;
public class testEscapeHTML{
	public static void main(String args[]){
	    String testString = "< > \" &";
	    System.out.println("Original : " + testString); 
            System.out.println("Escaped : " + StringEscapeUtils.escapeHtml(testString));



Original : ” & < >

Escaped : &quot; &amp; &lt; &gt;


About Mohaideen Jamil

I'm a Full stack developer of IT exp in J2EE, AngularJs, MicroServices, Docker, Spring (Boot, MVC, Cloud), Bluemix, DevOps. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

%d bloggers like this: