1.问题重现
页面数据
数据库数据
2.原因分析
为了防止xss攻击,会将所有传递进来的String进行HTML编码,一般使用StringEscapeUtils.escapeHtml4()方法,这个方法将<>转换为“&l.t;&.gt;
插入数据库是转义完成的,而这些字符浏览器可以解析回<>,事实上使用springmvc拦截器prehand和posthand中,数据均为<>
3.解决方式
使用拦截器,对所有service的增改方法进行拦截,对方法参数(即页面传过来的实体对象)的属性进行反转义,即StringEscapeUtils.unescapeHtml4()方法,保证操作数据库之前数据和页面一致。
public void unEscape(T entity) {
Field[] fields = entity.getClass().getDeclaredFields();
for(int i = 0;i < fields.length;i++) {
Field f = fields[i];
f.setAccessible(true);
try {
Object fieldValue = f.get(entity);
if(fieldValue != null && fieldValue instanceof String) {
fieldValue = StringEscapeUtils.unescapeHtml4(fieldValue.toString());
f.set(entity, fieldValue);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}