Escape special characters from String in Java + Mysql


Class StringEscapeUtils

java.lang.Object
extended by org.apache.commons.lang.StringEscapeUtils

public class StringEscapeUtils
extends java.lang.Object

Escapes and unescapes Strings for Java, Java Script, HTML, XML, and SQL.

escapeJava

public static void escapeJava(java.io.Writer out,
java.lang.String str)
throws java.io.IOException

Escapes the characters in a String using Java String rules to a Writer.

A null string input has no effect.

Parameters:
out – Writer to write escaped string into
str – String to escape values in, may be null
Throws:
java.lang.IllegalArgumentException – if the Writer is null
java.io.IOException – if error occurs on underlying Writer
See Also:
escapeJava(java.lang.String)

escapeJavaScript

public static java.lang.String escapeJavaScript(java.lang.String str)

Escapes the characters in a String using JavaScript String rules.

Escapes any values it finds into their JavaScript String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

So a tab becomes the characters ‘\\’ and ‘t’.

The only difference between Java strings and JavaScript strings is that in JavaScript, a single quote must be escaped.

Example:

input string: He didn’t say, “Stop!”
output string: He didn\’t say, \”Stop!\”

Parameters:
str – String to escape values in, may be null
Returns:
String with escaped values, null if null string input

Read More

Related Posts: