SpringMVC以数据绑定方式做HTML、SQL防注入

来源:互联网 发布:测试手机信号的软件 编辑:程序博客网 时间:2024/05/22 08:19
首先先定义个一个类集成 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 
@Controllerpublic 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注入。



                                             
0 0
原创粉丝点击