HTML Sanitizer Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓HTML Sanitizer runs in O(n) time and O(n) space, in Java as in every other language.
- ✓The JDK's only parser for markup, javax.xml.parsers.DocumentBuilder, insists on well-formed XML and rejects exactly the unclosed, mis-nested input that makes sanitizing necessary in the first place.
- ✓PolicyFactory is immutable and thread-safe, so it belongs in a static final field assembled once during class initialisation, and any Pattern it references belongs there too rather than being recompiled per request.
- ✓The Java trap: Java's fluent APIs return new objects and javac has no mechanism to insist you keep them. PolicyFactory.and(other) produces a combined policy and leaves the receiver untouched, so writing policy.and(Sanitizers.LINKS); as a statement compiles, allocates, runs and achieves nothing, with no warning from the compiler and no annotation in the JDK to request one.
- ✓The cost concentrates in the young generation: a String per attribute value, per text run and per rebuilt name, nearly all of it dead before the response is written, which is the allocation profile G1 handles best.
What HTML Sanitizer actually is
HTML Sanitizer in Java: what you actually reach for
Java implementation
import org.owasp.html.HtmlChangeListener;
import org.owasp.html.HtmlPolicyBuilder;
import org.owasp.html.PolicyFactory;
import java.util.regex.Pattern;
public final class IssueMarkup {
private static final Pattern HREF =
Pattern.compile("^(?:https:|mailto:|/|#)[^\\s]*$", Pattern.CASE_INSENSITIVE);
// PolicyFactory is immutable and thread safe, so build it once. Note that
// and() RETURNS the combined policy; calling it for effect compiles and
// silently does nothing, and javac has no @must_use to warn you.
private static final PolicyFactory POLICY = new HtmlPolicyBuilder()
.allowElements("p", "em", "code", "figure", "figcaption", "a")
.allowUrlProtocols("https", "mailto")
.allowAttributes("href").matching(HREF).onElements("a")
.allowAttributes("lang").onElements("p", "code")
.requireRelNofollowOnLinks()
.toFactory()
.and(org.owasp.html.Sanitizers.FORMATTING);
private IssueMarkup() { }
public static String clean(String fragment, StringBuilder dropped) {
// The three-argument overload reports what the policy threw away, so a
// silent empty result is distinguishable from "nothing was submitted".
return POLICY.sanitize(fragment, new HtmlChangeListener<StringBuilder>() {
@Override public void discardedTag(StringBuilder log, String element) {
log.append("tag:").append(element).append(' ');
}
@Override public void discardedAttributes(
StringBuilder log, String tag, String... names) {
for (String n : names) {
log.append(tag).append('@').append(n).append(' ');
}
}
}, dropped);
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for HTML Sanitizer?
The JDK's only parser for markup, javax.xml.parsers.DocumentBuilder, insists on well-formed XML and rejects exactly the unclosed, mis-nested input that makes sanitizing necessary in the first place. Two libraries own the real job: OWASP's Java HTML Sanitizer, where org.owasp.html.HtmlPolicyBuilder produces a PolicyFactory you call sanitize on and Sanitizers supplies ready-made FORMATTING, BLOCKS and LINKS policies; and jsoup, whose Jsoup.clean takes an org.jsoup.safety.Safelist, the class formerly named Whitelist. java.net.URI handles scheme inspection.
What is the most common Java mistake when implementing HTML Sanitizer?
Java's fluent APIs return new objects and javac has no mechanism to insist you keep them. PolicyFactory.and(other) produces a combined policy and leaves the receiver untouched, so writing policy.and(Sanitizers.LINKS); as a statement compiles, allocates, runs and achieves nothing, with no warning from the compiler and no annotation in the JDK to request one. The builder hides a quieter version of the same shape: allowAttributes("href") hands back an AttributeBuilder that only commits when onElements or globally is called, so an abandoned chain permits nothing while globally() permits it on every element.
How does HTML Sanitizer actually perform in Java?
The cost concentrates in the young generation: a String per attribute value, per text run and per rebuilt name, nearly all of it dead before the response is written, which is the allocation profile G1 handles best. What hurts is whatever escapes that pattern, chiefly a Pattern.compile inside the request path or a PolicyFactory rebuilt per call, which reassembles the entire element and attribute map. After a few thousand invocations the JIT inlines the allowlist HashSet.contains and the loop settles; the first requests after a deploy run interpreted and are measurably slower. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.