当Controller类只实现Controller 接口时,或者什么都不继承时设置转换器使用注解@InitBinder
@InitBinder
public void initBinder(WebDataBinder binder) {
// SimpleDateFormat dateFormat = new
// SimpleDateFormat("yyyy-MM-dd HH:mm");
// dateFormat.setLenient(false);
// binder.registerCustomEditor(Date.class, new
// CustomDateEditor(dateFormat, true));
// String类型转换,将所有传递进来的String进行HTML编码,防止XSS攻击
binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(text == null ? null : cleanXSS(text.trim()));
}
@Override
public String getAsText() {
Object value = getValue();
return value != null ? value.toString() : "";
}
});
}
/**
* 过滤html js字符串,避免xss攻击
*
* @param value
* @return
*/
private String cleanXSS(String value) {
// You'll need to remove the spaces from the html entities below
value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
value = value.replaceAll("'", "& #39;");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']",
"\"\"");
value = value.replaceAll("script", "");
return value;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
// SimpleDateFormat dateFormat = new
// SimpleDateFormat("yyyy-MM-dd HH:mm");
// dateFormat.setLenient(false);
// binder.registerCustomEditor(Date.class, new
// CustomDateEditor(dateFormat, true));
// String类型转换,将所有传递进来的String进行HTML编码,防止XSS攻击
binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(text == null ? null : cleanXSS(text.trim()));
}
@Override
public String getAsText() {
Object value = getValue();
return value != null ? value.toString() : "";
}
});
}
/**
* 过滤html js字符串,避免xss攻击
*
* @param value
* @return
*/
private String cleanXSS(String value) {
// You'll need to remove the spaces from the html entities below
value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
value = value.replaceAll("'", "& #39;");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']",
"\"\"");
value = value.replaceAll("script", "");
return value;
}