html工具类(jsoup相关)

本文介绍了一个用于清理HTML的工具——SishuokCleaner,该工具可以确保用户提供的HTML只包含预期的元素和属性,避免垃圾信息和跨站脚本攻击。通过白名单配置,可以精确控制哪些HTML标签和属性被允许。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.sishuok.es.common.utils.html.jsoup;

import org.jsoup.helper.Validate;
import org.jsoup.nodes.*;
import org.jsoup.parser.Tag;

import java.util.List;

/**
 * The whitelist based HTML cleaner. Use to ensure that end-user provided HTML contains only the elements and attributes
 * that you are expecting; no junk, and no cross-site scripting attacks!
 * <p/>
 * The HTML cleaner parses the input as HTML and then runs it through a white-list, so the output HTML can only contain
 * HTML that is allowed by the whitelist.
 * <p/>
 * It is assumed that the input HTML is a body fragment; the clean methods only pull from the source's body, and the
 * canned white-lists only allow body contained tags.
 * <p/>
 * Rather than interacting directly with a Cleaner object, generally see the {@code clean} methods in {@link org.jsoup.Jsoup}.
 */
public class SishuokCleaner {
    private SishuokWhitelist whitelist;

    /**
     * Create a new cleaner, that sanitizes documents using the supplied whitelist.
     *
     * @param whitelist white-list to clean with
     */
    public SishuokCleaner(SishuokWhitelist whitelist) {
        Validate.notNull(whitelist);
        this.whitelist = whitelist;
    }

    /**
     * Creates a new, clean document, from the original dirty document, containing only elements allowed by the whitelist.
     * The original document is not modified. Only elements from the dirt document's <code>body</code> are used.
     *
     * @param dirtyDocument Untrusted base document to clean.
     * @return cleaned document.
     */
    public Document clean(Document dirtyDocument) {
        Validate.notNull(dirtyDocument);

        Document clean = Document.createShell(dirtyDocument.baseUri());
        copySafeNodes(dirtyDocument.body(), clean.body());

        return clean;
    }

    /**
     * Dertmines if the input document is valid, against the whitelist. It is considered valid if all the tags and attributes
     * in the input HTML are allowed by the whitelist.
     * <p/>
     * This method can be used as a validator for user input forms. An invalid document will still be cleaned successfully
     * using the {@link #clean(org.jsoup.nodes.Document)} document. If using as a validator, it is recommended to still clean the document
     * to ensure enforced attributes are set correctly, and that the output is tidied.
     *
     * @param dirtyDocument document to test
     * @return true if no tags or attributes need to be removed; false if they do
     */
    public boolean isValid(Document dirtyDocument) {
        Validate.notNull(dirtyDocument);

        Document clean = Document.createShell(dirtyDocument.baseUri());
        int numDiscarded = copySafeNodes(dirtyDocument.body(), clean.body());
        return numDiscarded == 0;
    }

    /**
     * Iterates the input and copies trusted nodes (tags, attributes, text) into the destination.
     *
     * @param source source of HTML
     * @param dest   destination element to copy into
     * @return number of discarded elements (that were considered unsafe)
     */
    private int copySafeNodes(Element source, Element dest) {
        List<Node> sourceChildren = source.childNodes();
        int numDiscarded = 0;

        for (Node sourceChild : sourceChildren) {
            if (sourceChild instanceof Element) {
                Element sourceEl = (Element) sourceChild;

                if (whitelist.isSafeTag(sourceEl.tagName())) { // safe, clone and copy safe attrs
                    ElementMeta meta = createSafeElement(sourceEl);
                    Element destChild = meta.el;
                    dest.appendChild(destChild);

                    numDiscarded += meta.numAttribsDiscarded;
                    numDiscarded += copySafeNodes(sourceEl, destChild); // recurs
                } else { // not a safe tag, but it may have children (els or text) that are, so recurse
                    numDiscarded++;
                    numDiscarded += copySafeNodes(sourceEl, dest);
                }
            } else if (sourceChild instanceof TextNode) {
                TextNode sourceText = (TextNode) sourceChild;
                TextNode destText = new TextNode(sourceText.getWholeText(), sourceChild.baseUri());
                dest.appendChild(destText);
            } // else, we don't care about comments, xml proc instructions, etc
        }
        return numDiscarded;
    }

    private ElementMeta createSafeElement(Element sourceEl) {
        String sourceTag = sourceEl.tagName();
        Attributes destAttrs = new Attributes();
        Element dest = new Element(Tag.valueOf(sourceTag), sourceEl.baseUri(), destAttrs);
        int numDiscarded = 0;

        Attributes sourceAttrs = sourceEl.attributes();
        for (Attribute sourceAttr : sourceAttrs) {
            if (whitelist.isSafeAttribute(sourceTag, sourceEl, sourceAttr))
                destAttrs.put(sourceAttr);
            else
                numDiscarded++;
        }
        Attributes enforcedAttrs = whitelist.getEnforcedAttributes(sourceTag);
        destAttrs.addAll(enforcedAttrs);

        return new ElementMeta(dest, numDiscarded);
    }

    private static class ElementMeta {
        Element el;
        int numAttribsDiscarded;

        ElementMeta(Element el, int numAttribsDiscarded) {
            this.el = el;
            this.numAttribsDiscarded = numAttribsDiscarded;
        }
    }

}


package com.sishuok.es.common.utils.html.jsoup;

/*
    Thank you to Ryan Grove (wonko.com) for the Ruby HTML cleaner http://github.com/rgrove/sanitize/, which inspired
    this whitelist configuration, and the initial defaults.
 */

import org.jsoup.helper.Validate;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


/**
 * SishuokWhitelists define what HTML (elements and attributes) to allow through the cleaner. Everything else is removed.
 * <p/>
 * Start with one of the defaults:
 * <ul>
 * <li>{@link #none}
 * <li>{@link #simpleText}
 * <li>{@link #basic}
 * <li>{@link #basicWithImages}
 * <li>{@link #relaxed}
 * </ul>
 * <p/>
 * If you need to allow more through (please be careful!), tweak a base whitelist with:
 * <ul>
 * <li>{@link #addTags}
 * <li>{@link #addAttributes}
 * <li>{@link #addEnforcedAttribute}
 * <li>{@link #addProtocols}
 * </ul>
 * <p/>
 * The cleaner and these whitelists assume that you want to clean a <code>body</code> fragment of HTML (to add user
 * supplied HTML into a templated page), and not to clean a full HTML document. If the latter is the case, either wrap the
 * document HTML around the cleaned body HTML, or create a whitelist that allows <code>html</code> and <code>head</code>
 * elements as appropriate.
 * <p/>
 * If you are going to extend a whitelist, please be very careful. Make sure you understand what attributes may lead to
 * XSS attack vectors. URL attributes are particularly vulnerable and require careful validation. See
 * http://ha.ckers.org/xss.html for some XSS attack examples.
 *
 * @author Jonathan Hedley
 */
public class SishuokWhitelist {
    private Set<TagName> tagNames; // tags allowed, lower case. e.g. [p, br, span]
    private Map<TagName, Set<AttributeKey>> attributes; // tag -> attribute[]. allowed attributes [href] for a tag.
    private Map<TagName, Map<AttributeKey, AttributeValue>> enforcedAttributes; // always set these attribute values
    private Map<TagName, Map<AttributeKey, Set<Protocol>>> protocols; // allowed URL protocols for attributes

    /**
     * This whitelist allows only text nodes: all HTML will be stripped.
     *
     * @return whitelist
     */
    public static SishuokWhitelist none() {
        return new SishuokWhitelist();
    }

    /**
     * This whitelist allows only simple text formatting: <code>b, em, i, strong, u</code>. All other HTML (tags and
     * attributes) will be removed.
     *
     * @return whitelist
     */
    public static SishuokWhitelist simpleText() {
        return new SishuokWhitelist()
                .addTags("b", "em", "i", "strong", "u")
                ;
    }

    /**
     * This whitelist allows a fuller range of text nodes: <code>a, b, blockquote, br, cite, code, dd, dl, dt, em, i, li,
     * ol, p, pre, q, small, strike, strong, sub, sup, u, ul</code>, and appropriate attributes.
     * <p/>
     * Links (<code>a</code> elements) can point to <code>http, https, ftp, mailto</code>, and have an enforced
     * <code>rel=nofollow</code> attribute.
     * <p/>
     * Does not allow images.
     *
     * @return whitelist
     */
    public static SishuokWhitelist basic() {
        return new SishuokWhitelist()
                .addTags(
                        "a", "b", "blockquote", "br", "cite", "code", "dd", "dl", "dt", "em",
                        "i", "li", "ol", "p", "pre", "q", "small", "strike", "strong", "sub",
                        "sup", "u", "ul")

                .addAttributes("a", "href")
                .addAttributes("blockquote", "cite")
                .addAttributes("q", "cite")

                .addProtocols("a", "href", "ftp", "http", "https", "mailto")
                .addProtocols("blockquote", "cite", "http", "https")
                .addProtocols("cite", "cite", "http", "https")

                .addEnforcedAttribute("a", "rel", "nofollow")
                ;

    }

    /**
     * This whitelist allows the same text tags as {@link #basic}, and also allows <code>img</code> tags, with appropriate
     * attributes, with <code>src</code> pointing to <code>http</code> or <code>https</code>.
     *
     * @return whitelist
     */
    public static SishuokWhitelist basicWithImages() {
        return basic()
                .addTags("img")
                .addAttributes("img", "align", "alt", "height", "src", "title", "width")
                .addProtocols("img", "src", "http", "https")
                ;
    }

    /**
     * This whitelist allows a full range of text and structural body HTML: <code>a, b, blockquote, br, caption, cite,
     * code, col, colgroup, dd, dl, dt, em, h1, h2, h3, h4, h5, h6, i, img, li, ol, p, pre, q, small, strike, strong, sub,
     * sup, table, tbody, td, tfoot, th, thead, tr, u, ul</code>
     * <p/>
     * Links do not have an enforced <code>rel=nofollow</code> attribute, but you can add that if desired.
     *
     * @return whitelist
     */
    public static SishuokWhitelist relaxed() {
        return new SishuokWhitelist()
                .addTags(
                        "a", "b", "blockquote", "br", "caption", "cite", "code", "col",
                        "colgroup", "dd", "div", "dl", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6",
                        "i", "img", "li", "ol", "p", "pre", "q", "small", "strike", "strong",
                        "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u",
                        "ul")

                .addAttributes("a", "href", "title")
                .addAttributes("blockquote", "cite")
                .addAttributes("col", "span", "width")
                .addAttributes("colgroup", "span", "width")
                .addAttributes("img", "align", "alt", "height", "src", "title", "width")
                .addAttributes("ol", "start", "type")
                .addAttributes("q", "cite")
                .addAttributes("table", "summary", "width")
                .addAttributes("td", "abbr", "axis", "colspan", "rowspan", "width")
                .addAttributes(
                        "th", "abbr", "axis", "colspan", "rowspan", "scope",
                        "width")
                .addAttributes("ul", "type")

                .addProtocols("a", "href", "ftp", "http", "https", "mailto")
                .addProtocols("blockquote", "cite", "http", "https")
                .addProtocols("img", "src", "http", "https")
                .addProtocols("q", "cite", "http", "https")
                ;
    }

    /**
     * Create a new, empty whitelist. Generally it will be better to start with a default prepared whitelist instead.
     *
     * @see #basic()
     * @see #basicWithImages()
     * @see #simpleText()
     * @see #relaxed()
     */
    public SishuokWhitelist() {
        tagNames = new HashSet<TagName>();
        attributes = new HashMap<TagName, Set<AttributeKey>>();
        enforcedAttributes = new HashMap<TagName, Map<AttributeKey, AttributeValue>>();
        protocols = new HashMap<TagName, Map<AttributeKey, Set<Protocol>>>();
    }

    /**
     * Add a list of allowed elements to a whitelist. (If a tag is not allowed, it will be removed from the HTML.)
     *
     * @param tags tag names to allow
     * @return this (for chaining)
     */
    public SishuokWhitelist addTags(String... tags) {
        Validate.notNull(tags);

        for (String tagName : tags) {
            Validate.notEmpty(tagName);
            tagNames.add(TagName.valueOf(tagName));
        }
        return this;
    }

    /**
     * Add a list of allowed attributes to a tag. (If an attribute is not allowed on an element, it will be removed.)
     * <p/>
     * To make an attribute valid for <b>all tags</b>, use the pseudo tag <code>:all</code>, e.g.
     * <code>addAttributes(":all", "class")</code>.
     *
     * @param tag  The tag the attributes are for
     * @param keys List of valid attributes for the tag
     * @return this (for chaining)
     */
    public SishuokWhitelist addAttributes(String tag, String... keys) {
        Validate.notEmpty(tag);
        Validate.notNull(keys);

        TagName tagName = TagName.valueOf(tag);
        Set<AttributeKey> attributeSet = new HashSet<AttributeKey>();
        for (String key : keys) {
            Validate.notEmpty(key);
            attributeSet.add(AttributeKey.valueOf(key));
        }
        if (attributes.containsKey(tagName)) {
            Set<AttributeKey> currentSet = attributes.get(tagName);
            currentSet.addAll(attributeSet);
        } else {
            attributes.put(tagName, attributeSet);
        }
        return this;
    }

    /**
     * Add an enforced attribute to a tag. An enforced attribute will always be added to the element. If the element
     * already has the attribute set, it will be overridden.
     * <p/>
     * E.g.: <code>addEnforcedAttribute("a", "rel", "nofollow")</code> will make all <code>a</code> tags output as
     * <code><a href="..." rel="nofollow"></code>
     *
     * @param tag   The tag the enforced attribute is for
     * @param key   The attribute key
     * @param value The enforced attribute value
     * @return this (for chaining)
     */
    public SishuokWhitelist addEnforcedAttribute(String tag, String key, String value) {
        Validate.notEmpty(tag);
        Validate.notEmpty(key);
        Validate.notEmpty(value);

        TagName tagName = TagName.valueOf(tag);
        AttributeKey attrKey = AttributeKey.valueOf(key);
        AttributeValue attrVal = AttributeValue.valueOf(value);

        if (enforcedAttributes.containsKey(tagName)) {
            enforcedAttributes.get(tagName).put(attrKey, attrVal);
        } else {
            Map<AttributeKey, AttributeValue> attrMap = new HashMap<AttributeKey, AttributeValue>();
            attrMap.put(attrKey, attrVal);
            enforcedAttributes.put(tagName, attrMap);
        }
        return this;
    }

    /**
     * Add allowed URL protocols for an element's URL attribute. This restricts the possible values of the attribute to
     * URLs with the defined protocol.
     * <p/>
     * E.g.: <code>addProtocols("a", "href", "ftp", "http", "https")</code>
     *
     * @param tag       Tag the URL protocol is for
     * @param key       Attribute key
     * @param protocols List of valid protocols
     * @return this, for chaining
     */
    public SishuokWhitelist addProtocols(String tag, String key, String... protocols) {
        Validate.notEmpty(tag);
        Validate.notEmpty(key);
        Validate.notNull(protocols);

        TagName tagName = TagName.valueOf(tag);
        AttributeKey attrKey = AttributeKey.valueOf(key);
        Map<AttributeKey, Set<Protocol>> attrMap;
        Set<Protocol> protSet;

        if (this.protocols.containsKey(tagName)) {
            attrMap = this.protocols.get(tagName);
        } else {
            attrMap = new HashMap<AttributeKey, Set<Protocol>>();
            this.protocols.put(tagName, attrMap);
        }
        if (attrMap.containsKey(attrKey)) {
            protSet = attrMap.get(attrKey);
        } else {
            protSet = new HashSet<Protocol>();
            attrMap.put(attrKey, protSet);
        }
        for (String protocol : protocols) {
            Validate.notEmpty(protocol);
            Protocol prot = Protocol.valueOf(protocol);
            protSet.add(prot);
        }
        return this;
    }

    boolean isSafeTag(String tag) {
        return tagNames.contains(TagName.valueOf(tag));
    }

    boolean isSafeAttribute(String tagName, Element el, Attribute attr) {
        TagName tag = TagName.valueOf(tagName);
        if (attributes.containsKey(tag)) {
            for (AttributeKey attributeKey : attributes.get(tag)) {
                if (attr.getKey().startsWith(attributeKey.toString())) {
                    return false;
                }
            }
            return true;
        } else { // no attributes defined for tag, try :all tag
            return !tagName.equals(":all") && isSafeAttribute(":all", el, attr);
        }
    }

    private boolean testValidProtocol(Element el, Attribute attr, Set<Protocol> protocols) {
        // resolve relative urls to abs, and update the attribute so output html has abs.
        // rels without a baseuri get removed
        String value = el.absUrl(attr.getKey());
        attr.setValue(value);

        for (Protocol protocol : protocols) {
            String prot = protocol.toString() + ":";
            if (value.toLowerCase().startsWith(prot)) {
                return true;
            }
        }
        return false;
    }

    Attributes getEnforcedAttributes(String tagName) {
        Attributes attrs = new Attributes();
        TagName tag = TagName.valueOf(tagName);
        if (enforcedAttributes.containsKey(tag)) {
            Map<AttributeKey, AttributeValue> keyVals = enforcedAttributes.get(tag);
            for (Map.Entry<AttributeKey, AttributeValue> entry : keyVals.entrySet()) {
                attrs.put(entry.getKey().toString(), entry.getValue().toString());
            }
        }
        return attrs;
    }

    // named types for config. All just hold strings, but here for my sanity.

    static class TagName extends TypedValue {
        TagName(String value) {
            super(value);
        }

        static TagName valueOf(String value) {
            return new TagName(value);
        }
    }

    static class AttributeKey extends TypedValue {
        AttributeKey(String value) {
            super(value);
        }

        static AttributeKey valueOf(String value) {
            return new AttributeKey(value);
        }
    }

    static class AttributeValue extends TypedValue {
        AttributeValue(String value) {
            super(value);
        }

        static AttributeValue valueOf(String value) {
            return new AttributeValue(value);
        }
    }

    static class Protocol extends TypedValue {
        Protocol(String value) {
            super(value);
        }

        static Protocol valueOf(String value) {
            return new Protocol(value);
        }
    }

    abstract static class TypedValue {
        private String value;

        TypedValue(String value) {
            Validate.notNull(value);
            this.value = value;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((value == null) ? 0 : value.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) return true;
            if (obj == null) return false;
            if (getClass() != obj.getClass()) return false;
            TypedValue other = (TypedValue) obj;
            if (value == null) {
                if (other.value != null) return false;
            } else if (!value.equals(other.value)) return false;
            return true;
        }

        @Override
        public String toString() {
            return value;
        }
    }
}


package com.sishuok.es.common.utils.html;

import com.sishuok.es.common.utils.html.jsoup.SishuokCleaner;
import com.sishuok.es.common.utils.html.jsoup.SishuokWhitelist;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

/**
 * html工具类
 * 主要作用:标签转义、提取摘要、删除不安全的tag(比如<script></script>)
 */
public class HtmlUtils {

    /**
     * 获取html文档中的文本
     *
     * @return
     */
    public static String text(String html) {
        if (StringUtils.isEmpty(html)) {
            return html;
        }
        return Jsoup.parse(removeUnSafeTag(html).replace("<", "<").replace(">", ">")).text();
    }

    /**
     * 获取html文档中的文本 并仅提取文本中的前maxLength个 超出部分使用……补充
     *
     * @param html
     * @param maxLength
     * @return
     */
    public static String text(String html, int maxLength) {
        String text = text(html);
        if (text.length() <= maxLength) {
            return text;
        }
        return text.substring(0, maxLength) + "……";
    }

    /**
     * 从html中移除不安全tag
     *
     * @param html
     * @return
     */
    public static String removeUnSafeTag(String html) {
        SishuokWhitelist whitelist = new SishuokWhitelist();
        whitelist.addTags("embed", "object", "param", "span", "div", "img", "font", "del");
        whitelist.addTags("a", "b", "blockquote", "br", "caption", "cite", "code", "col", "colgroup");
        whitelist.addTags("dd", "dl", "dt", "em", "hr", "h1", "h2", "h3", "h4", "h5", "h6", "i", "img");
        whitelist.addTags("li", "ol", "p", "pre", "q", "small", "strike", "strong", "sub", "sup", "table");
        whitelist.addTags("tbody", "td", "tfoot", "th", "thead", "tr", "u", "ul");

        //删除以on开头的(事件)
        whitelist.addAttributes(":all", "on");
        Document dirty = Jsoup.parseBodyFragment(html, "");
        SishuokCleaner cleaner = new SishuokCleaner(whitelist);
        Document clean = cleaner.clean(dirty);

        return clean.body().html();
    }

    /**
     * 删除指定标签
     *
     * @param html
     * @param tagName
     * @return
     */
    public static String removeTag(String html, String tagName) {
        Element bodyElement = Jsoup.parse(html).body();
        bodyElement.getElementsByTag(tagName).remove();
        return bodyElement.html();
    }

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值