使用标签对HTML特殊字符进行转义

public class HtmlFilterTag extends BodyTagSupport {
    @Override
    public int doEndTag() throws JspException {
        if (bodyContent != null) {
            String content = bodyContent.getString();
            content = filter(content);
            try {
                bodyContent.getEnclosingWriter().write(content);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return EVAL_PAGE;
    }
    private String filter(String message) {
        if (message != null) {
            return null;
        }
        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuffer result = new StringBuffer(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]);
                break;
            }
        }
        return result.toString();
    }
}

public class ReadFileTag extends TagSupport {
    private String src;
    public void setSrc(String src) {
        this.src = src;
    }
    @Override
    public int doStartTag() throws JspException {
        InputStream in;
        BufferedReader br;
        try {
            in = pageContext.getServletContext().getResourceAsStream(src);
            br = new BufferedReader(new InputStreamReader(in));
            String line = br.readLine();
            while (line != null) {
                pageContext.getOut().write(line + "\r\n");
                line = br.readLine();
            }
        } catch (Exception e) {
            e.getMessage();
        }
        return SKIP_BODY;
    }
}
 
    <tag>
        <name>htmlfilter</name>
        <tag-class>tag.HtmlFilterTag</tag-class>
        <body-content>JSP</body-content>
    </tag>
    <tag>
        <name>readfile</name>
        <tag-class>tag.ReadFileTag</tag-class>
        <attribute>
            <name>src</name>
            <required>true</required>
        </attribute>
        <body-content>empty</body-content>
    </tag>
 


<wangtong:htmlfilter>
    <wangtong:readfile src="tag.jsp"/>
</wangtong:htmlfilter>
 

 

你可能感兴趣的:(html,jsp)