SpringMVC以資料繫結方式做HTML、SQL防注入
阿新 • • 發佈:2018-12-25
首先先定義個一個類整合 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注入。