/**
* Xss处理工具类
*/
public class XssUtil {
private static Logger logger = LoggerFactory.getLogger(XssUtil.class);
/**
* 预处理JavaBean的String类型属性中的Xss代码
* @param bean
* @param escape 是否转义,如果escape=true,则进行转义处理;否则,进行转义还原处理。
*/
public static void preProcessXssCode(Object bean, boolean escape) {
if (null == bean || bean.getClass().isPrimitive()) return;
Class<?> clazz = bean.getClass();
PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(clazz);
for (PropertyDescriptor pd : pds) {
if (String.class == pd.getPropertyType()) {
try {
String str = (String) pd.getReadMethod().invoke(bean);
pd.getWriteMethod().invoke(bean, preProcessXssCode(str, escape));
} catch (Exception e) {
logger.warn("failed to unescape string property '{}' of {}, cause of:{}",
new Object[] { pd.getName(), clazz, e });
}
}
}
}
/**
* 预处理Xss代码
* @param str
* @param escape 是否转义,如果escape=true,则进行转义处理;否则,进行转义还原处理。
*/
public static String preProcessXssCode(String str, boolean escape) {
String s = str;
if (null != str && str.length() > 0) {
if (escape) {
// 先做一次unescape将原文本中已经转义的html代码还原,再做转义处理
// 这样可以避免直接转义造成原文本中已转义的html代码被二次转义
s = HtmlUtils.htmlUnescape(s);
s = HtmlUtils.htmlEscape(s);
} else {
s = HtmlUtils.htmlUnescape(s);
}
}
return s;
}
}
网友评论