XSS Prevention 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
- ✓XSS Prevention runs in O(n) time and O(n) space, in Java as in every other language.
- ✓The JDK ships no HTML escaper. java.net.URLEncoder exists but is form encoding, turning a space into a plus sign, which is wrong in a path segment.
- ✓Reviewers expect a per-context Encode call rather than one escape helper reused everywhere, and Thymeleaf th:text over th:utext, with any th:utext accompanied by a sanitiser on the same value.
- ✓The Java trap: StringEscapeUtils.escapeHtml4 escapes the named HTML 4 entities and does not touch the apostrophe, because HTML 4 has no apos entity, so a value dropped into a single-quoted attribute escapes out of it while looking fully escaped in the diff.
- ✓Strings are immutable, so every encoder call allocates a fresh char array; escaping fifty columns of a thousand-row table is fifty thousand short-lived objects, cheap in the young generation but not free, and it is why encoders that can write straight into the response Writer are preferred over ones that return a String.
What XSS Prevention actually is
XSS Prevention in Java: what you actually reach for
Java implementation
import org.owasp.encoder.Encode;
import org.owasp.html.PolicyFactory;
import org.owasp.html.Sanitizers;
// Immutable and thread-safe: build once, share across requests.
static final PolicyFactory BIO = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
static String link(String url, String label) {
// Four contexts, four encoders. Commons Text escapeHtml4 would leave the
// apostrophe alone, which is fatal inside a single-quoted attribute.
// Encoding is not a scheme check, so do that separately.
String safeUrl = url.startsWith("https://") || url.startsWith("/") ? url : "#";
return "<a href=\"" + Encode.forHtmlAttribute(safeUrl) + "\">"
+ Encode.forHtml(label) + "</a>";
}
static String scriptVar(String name) {
return "<script>var u = \"" + Encode.forJavaScript(name) + "\";</script>";
}
static String search(String q) {
// URLEncoder is form encoding: space becomes '+', wrong in a path.
return "/search?q=" + Encode.forUriComponent(q);
}
static String bio(String html) { return BIO.sanitize(html); }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 XSS Prevention?
The JDK ships no HTML escaper. java.net.URLEncoder exists but is form encoding, turning a space into a plus sign, which is wrong in a path segment. The context-sensitive API the ecosystem settled on is OWASP Java Encoder: Encode.forHtml, forHtmlAttribute, forHtmlUnquotedAttribute, forJavaScript, forCssString and forUriComponent are separate methods precisely because they are separate grammars. Apache Commons Text StringEscapeUtils is the fallback after the commons-lang3 copy was deprecated in 3.6. Rich text goes through OWASP Java HTML Sanitizer, via HtmlPolicyBuilder or the prebuilt Sanitizers policies.
What is the most common Java mistake when implementing XSS Prevention?
StringEscapeUtils.escapeHtml4 escapes the named HTML 4 entities and does not touch the apostrophe, because HTML 4 has no apos entity, so a value dropped into a single-quoted attribute escapes out of it while looking fully escaped in the diff. In JSP, an expression like ${param.q} is not escaped at all; expression language was never an escaping mechanism, and only c:out or fn:escapeXml adds one, which is why legacy pages leak while newer Thymeleaf pages beside them do not. And URLEncoder.encode, the reflex import for anything URL-shaped, emits plus-for-space form encoding that is simply wrong inside a path or an href.
How does XSS Prevention actually perform in Java?
Strings are immutable, so every encoder call allocates a fresh char array; escaping fifty columns of a thousand-row table is fifty thousand short-lived objects, cheap in the young generation but not free, and it is why encoders that can write straight into the response Writer are preferred over ones that return a String. A hand-rolled chain of five String.replace calls allocates five intermediates per value. Template engines cache the parsed template, so the steady-state cost per request is the escape scan, not parsing. 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? Student discounts on developer tools are collected on Noizz, tool by tool.
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.