Pages Navigation Menu

Coding is much easier than you think

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));
	}
}

 

Result

Original : ” & < >

Escaped : " & < >

Reference

http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html