Java code to filter Cross site scripting
Filter intercepts every request sent to your web application and then cleans any potential script injection. This code remove all suspicious strings from request parameters before returning them to the application.
private String cleanXSS(final String paramString) {
if (paramString == null)
return "";
String str = paramString;
str = str.replaceAll("", "");
Pattern localPattern = Pattern.compile("<script>(.*?)</script>", 2);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("src[rn]*=[rn]*'(.*?)'", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("src[rn]*=[rn]*\"(.*?)\"", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("</script>", 2);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("<script(.*?)>", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("eval\((.*?)\)", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("expression\((.*?)\)", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("javascript:", 2);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("vbscript:", 2);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("onload(.*?)=", 42);
str = localPattern.matcher(str).replaceAll("");
str = str.replaceAll("\(", "(").replaceAll("\)", ")");
str = str.replaceAll("'", "'");
str = str.replaceAll("<", "<").replaceAll(">", ">");
return str;
}

