javaWeb 使用jsp开发 html过滤标签

1.jsp调用代码

<t:htmlFilter>
    <a href="${pageContext.request.contextPath }/index.jsp">link</a>
</t:htmlFilter>

2.tld文件代码

<tag>
    <name>htmlFilter</name>
    <tag-class>de.bvb.web.tag.HtmlFilterTag</tag-class>
    <body-content>scriptless</body-content>
</tag>

3.标签实现类代码

package de.bvb.web.tag;

import java.io.IOException;
import java.io.StringWriter;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class HtmlFilterTag extends SimpleTagSupport {
    @Override
    public void doTag() throws JspException, IOException {
        StringWriter sw = new StringWriter();
        JspFragment jf = this.getJspBody();
        jf.invoke(sw);
        String content = sw.getBuffer().toString();
        content = filter(content);
        ((PageContext) this.getJspContext()).getOut().write(content);
    }

    //copy from apache-tomcat-8.0.9/webapps/examples/WEB-INF/classes/util/HTMLFilter.java
    public String filter(String message) {
        if (message == null)
            return (null);
        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuilder result = new StringBuilder(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
            case '<':
                result.append("&lt;");
                break;
            case '>':
                result.append("&gt;");
                break;
            case '&':
                result.append("&amp;");
                break;
            case '"':
                result.append("&quot;");
                break;
            default:
                result.append(content[i]);
            }
        }
        return (result.toString());
    }
}

 

posted @ 2016-10-19 21:59  MarcoReus  阅读(1135)  评论(0编辑  收藏  举报