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

Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.