ludc
2025-01-16 5203081b68e3a8dc139d1807b2f8774e4a00a82a
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.vci.starter.web.toolmodel;
 
import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.JavaScriptUtils;
 
import java.beans.PropertyEditorSupport;
 
/**
 * 与spring mvc的@InitBinder结合
 * 用于防止XSS攻击
 * 将Html中包含的js等相关的内容转换
 * @author weidy
 * 
 */
public class StringEscapeEditor extends PropertyEditorSupport {
 
    /**
     * 要编码的HTML内容
     */
    private boolean escapeHTML;// 编码HTML
    /**
     * 要编码的js
     */
    private boolean escapeJavaScript;// 编码javascript
 
    /**
     * 构造方法
     */
    public StringEscapeEditor() {
        super();
    }
 
    /**
     * 构造方法
     * @param escapeHTML 要编码的html
     * @param escapeJavaScript 要编码的JS
     */
    public StringEscapeEditor(boolean escapeHTML, boolean escapeJavaScript) {
        super();
        this.escapeHTML = escapeHTML;
        this.escapeJavaScript = escapeJavaScript;
    }
 
    /**
     * 执行转换
     * @return 编码后的内容
     */
    @Override
    public String getAsText() {
        Object value = getValue();
        return value != null ? value.toString() : "";
    }
 
    /**
     * 执行专家
     * @param text 转换钱的值
     * @throws IllegalArgumentException 转换的过程出现了错误会抛出异常
     */
    @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);
        }
    }
 
}