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);
|
}
|
}
|
|
}
|