jsp自定义标签过滤XSS安全字符

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

 

结果:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勇气heart

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值