zhuguifei
2026-03-10 58402bd5e762361363a0f7d7907153c77dbb819f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.shlanbao.tzsc.utils.extents;
 
import java.beans.PropertyEditorSupport;
 
import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.JavaScriptUtils;
 
/**
 * 与spring mvc的@InitBinder结合
 * 
 * 用于防止XSS攻击
 * 
 * @author 孙宇
 * 
 */
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);
        }
    }
 
}