|
对于封装好的 form 以及 pojo 层对象的Strng字段进行HTML字符过滤。
思路:
1 通过传入对象 ,对象类型名, 获取出对象自己的getter and setter 方法, 并将其对应到 map 中
2 判断 其get方法的返回值类型, 若是string 类型 则调用对应属性的getter
3 将得到的字符串通过StringFilte 进行过滤后 ,调用对象的setter 将其保存到对象中完成过滤。
import java.util.*;
import java.lang.reflect.*;
public class SuperFilter {
private Object obj; // 传入的对象
private List< String> Methodname = new ArrayList< String>(); // 方法名
private Map< String, Mobj> map = new HashMap< String, Mobj>();
private List< Method> getList = new ArrayList< Method>(); // get 方法列表
private List< Method> setList = new ArrayList< Method>();// set 方法列表
public SuperFilter(Object obj, Class< ?> cla) {
this.obj = obj;
String style = cla.getName();
MethodSorter(obj, style);
MethodFilter();
}
public SuperFilter(Object obj, String style) {
this.obj = obj;
MethodSorter(obj, style);
MethodFilter();
}
private void MethodSorter(Object o, String name) {
Method methods[] = null;
try {
methods = Class.forName(name).getDeclaredMethods();
} catch (SecurityException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < methods.length; i++) {
Method m = methods;
if (m.getName().startsWith("get")) {
getList.add(m);
String tempname = m.getName();
Methodname.add(tempname.substring(3));
}
if (m.getName().startsWith("set")) {
setList.add(m);
}
}
for (int i = 0; i < Methodname.size(); i++) {
String temp = Methodname.get(i);
for (int m = 0; m < setList.size(); m++) {
Method met = setList.get(m);
if (met.getName().endsWith(temp)) {
map.put(temp, new Mobj(getList.get(i), met));
}
}
}
}
public void MethodFilter() {
for (int i = 0; i < Methodname.size(); i++) {
Mobj mobj = map.get(Methodname.get(i));
Method methodget = mobj.getGetMethod();
Method methodset = mobj.getSetMethod();
try {
if (String.class.isInstance(methodget.invoke(obj, null))) {
String temp = (String) methodget.invoke(obj, null);
// System.out.println("~~~~~~~~~~~~~~~~~~");
System.out.println(temp);
// System.out.println("~~~~~~~~~~~~~~~~~~");
String tempAfterFilter = StringFilter.filterHtml(temp);
methodset.invoke(obj, tempAfterFilter);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
protected class Mobj {
Method getMethod;
Method setMethod;
public Mobj(Method getMethod, Method setMethod) {
this.getMethod = getMethod;
this.setMethod = setMethod;
}
public Method getSetMethod() {
return setMethod;
}
public void setSetMethod(Method setMethod) {
this.setMethod = setMethod;
}
public Method getGetMethod() {
return getMethod;
}
public void setGetMethod(Method getMethod) {
this.getMethod = getMethod;
}
}
} |
|