Friday, June 18, 2010

How to escape special characters in java


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) '
5) \
6) &

Here i want to introduce a handy-ready java library call StringEscapeUtils which included in commons-lang.jar library, and used to escape special characters in Java.

P.S Please download the commons-lang.jar library in http://commons.apache.org/lang/

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 testStr = "< > \" &";
 
System.out.println("Original : " + testStr);
 
System.out.println("Escaped : " + StringEscapeUtils.escapeHtml(testStr));
 
}
}

Result

Original : < > " &
Escaped : &lt; &gt; &quot; &amp;

No comments:

Post a Comment