Pages Navigation Menu

Coding is much easier than you think

How To Escape Special Characters of JSP using Java code?

Posted by on Apr 18, 2013 in Java | 0 comments

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;


Read More