Archive for JSP

Java – How to escape String

Thursday, May 21st, 2009

String in HTML should not contain special characters. If String contains special character, it should escape string using StringEscapeUtil class.
This class can escape special characters from String. Final string comes with HTML code.

Download apache commons api

import org.apache.commons.lang.StringEscapeUtils;

public class EscapeString {

    public static void main(String[] args) {

        String str="<HTML> tag's value  \"into\" html & tag";

        String escapedString=StringEscapeUtils.escapeHtml(str);

        System.out.println(escapedString);
    }
}

Output

&lt;HTML&gt; tag’s value &quot;into&quot; html text &amp; tag