第一步:创建一个BaseController。
public class BaseController {
    /**
     * 重写方法
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
    }
 
第二步,创建所需的StringEscapeEditor类
import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.JavaScriptUtils;
import java.beans.PropertyEditorSupport;
/**
 * 转义工具类(主要针对xss攻击)
 */
public class StringEscapeEditor extends PropertyEditorSupport {
    private boolean escapeHTML;// 编码HTML
    private boolean escapeJavaScript;// 编码javascript
    public StringEscapeEditor() {
        super();
    }
    public StringEscapeEditor(boolean escapeHTML, boolean escapeJavaScript) {
        super();
        this.escapeHTML = escapeHTML;
        this.escapeJavaScript = escapeJavaScript;
    }
    @Override
    public String getAsText() {
        Object value = getValue();
        return value != null ? value.toString() : "";
    }
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text == null) {
            setValue(null);
        } else {
            String value = text;
            if (escapeHTML) {
                value = HtmlUtils.htmlEscape(value);
            }
            if (escapeJavaScript) {
                value = JavaScriptUtils.javaScriptEscape(value);
            }
            setValue(value);
        }
    }
}
 
第三步: 其他Controller 继承 BaseController
 
 知识点以及注意:
 1.主要是使用 HtmlUtils.htmlEscape(value)进行转义的.
 2.注意BaseController 上没有@controller注解.










