1.创建自定义标签类
public class XssTag extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
}
}
2.创建xss.tld文件,并注册标签类
<?xml version="1.0" encoding="ISO-8859-1"?>
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>xss-utils</short-name>
<tag>
<name>convert</name>
<tag-class>com.util.tag.XssTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
3.web.xml中添加配置
<jsp-config>
<taglib>
<taglib-uri>/myxss</taglib-uri>
<taglib-location>/WEB-INF/tld/xss.tld</taglib-location>
</taglib>
</jsp-config>
4.jsp中添加标签
<%@ taglib prefix="xss" uri="/myxss"%>
5.标签使用
<xss:convert value="#resMap.test" />
6.编辑自定义规则
@Override
public void doTag() throws JspException, IOException {
//ognl 取值
if (StringUtils.isNotBlank(value)) {
ValueStack valueStack = ActionContext.getContext().getValueStack();
if (null != valueStack) {
value = valueStack.findString(value);
}
}
if (!StringUtil.isBlank(value)){
//过滤 XSS
Set<String> xssNames = tagMap.keySet();
for (String xssName: xssNames ) {
String xssVal = tagMap.get(xssName);
value = value.replaceAll(xssName,xssVal);
}
}
// 输出
JspWriter writer = getJspContext().getOut();
writer.write(value);
writer.flush();
// 清理
value = null;
}
tagMap是封装过滤哪些标签,我这里把这些放在一个配置文件中,然后封装到tagMap中,通过配置黑名单来过滤标签。
#配置文件
#标签转换规则
< = <
> = >
" = "
' = '
String path = EnvironmentUtils.getClasspathRoot() + "xsstag.properties";
Properties properties = new Properties();
is =new BufferedInputStream(new FileInputStream(path));
inputStreamReader = new InputStreamReader(is, "utf-8");
properties.load(inputStreamReader);
Set<String> names = properties.stringPropertyNames();
for (String name: names) {
String value = properties.getProperty(name);
tagMap.put(name.trim(),value.trim());
}