有困难,找猪八戒
/** Given a string, this method replaces all occurrences of
* '<' with '<', all occurrences of '>' with
* '>', and (to handle cases that occur inside attribute
* values), all occurrences of double quotes with
* '"' and all occurrences of '&' with '&'.
* Without such filtering, an arbitrary string
* could not safely be inserted in a Web page.
*/
public static String filter(String input) {
if(!hasSpecialChars(input)){
return(input);
}
StringBuffer filtered = new StringBuffer(input.length());
char c;
for(int i=0; i<input.length(); i++) {
c = input.charAt(i);
if (c == '<') {
filtered.append("<");
} else if (c == '>') {
filtered.append(">");
} else if (c == '"') {
filtered.append(""");
} else if (c == '&') {
filtered.append("&");
} else {
filtered.append(c);
}
}
return(filtered.toString());
}
public static boolean hasSpecialChars(String input) {
boolean flag = false;
if((input !=null) && (input.length()>0)) {
char c;
for(int i=0; i<input.length();i++) {
c = input.charAt(i);
switch(c) {
case '<': flag = true; break;
case '>': flag = true; break;
case '"': flag = true; break;
case '&': flag = true; break;
}
}
}
}
有困难,找猪八戒