首先先定义个一个类集成 PropertyEditorSupport 属性编辑器
public class StringEscapeEditor extends PropertyEditorSupport {
private boolean escapeHTML; //定义是否是HTML注入
private boolean escapeSQL; //定义是否是SQL注入
public StringEscapeEditor() {
super();
}
public StringEscapeEditor(boolean escapeHTML, boolean escapeSQL) {
super();
this.escapeHTML = escapeHTML;
this.escapeSQL = escapeSQL;
}
@Override
public void setAsText(String text) {
if (text == null) {
setValue(null);
} else {
String value = text.trim();
if (escapeHTML) {
value = StringUtil.XMLEncNA(value);//freemarker工具类能使"","&"等转义
}
if (escapeSQL) {
value = StringEscapeUtils.escapeSql(value);//commons-lang工具类
}
setValue(value);
}
}
@Override
public String getAsText() {
Object value = getValue();
return value != null ? value.toString() : "";
}
}
写一个 BaseController
@Controller
public class BaseController {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringEscapeEditor(true, true));
binder.registerCustomEditor(String[].class, new StringEscapeEditor(true, true));
}
}
@InitBinder在跟表单绑定之前都会先注册这些编辑器
之后在某些想要防止HTML SQL注入类中extends BaseController就会自动把数据转义以防止HTML注入。