Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Introduction

Cross-Site Scripting (XSS) is a type of vulnerability that allows attackers to inject malicious scripts into web applications. Attackers can execute these scripts in the user’s browser, leading to data theft, session hijacking, or website defacement.

In this tutorial, we’ll explore how to sanitize HTML input in Java applications to prevent XSS attacks.

2. Setting up the Project

To begin with, we need to add the OWASP Java HTML sanitizer library to our pom.xml:

<dependency>
    <groupId>com.googlecode.owasp-java-html-sanitizer</groupId>
    <artifactId>owasp-java-html-sanitizer</artifactId>
    <version>20240325.1</version>
</dependency>

This library provides a highly configurable policy-driven sanitizer that can handle complex HTML while protecting against XSS attacks.

3. Implementing Basic OWASP HTML Sanitization

With the dependency in place, let’s define a utility method that uses the library to clean potentially harmful HTML input. We’ll create a reusable utility class that sanitizes HTML using a default policy that allows only basic formatting tags:

public class HtmlSanitizerUtil {
    private static final PolicyFactory POLICY = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    public static String sanitize(String htmlContent) {
        return POLICY.sanitize(htmlContent);
    }
}

In the example above, we configure a sanitization policy by combining two built-in sanitizers – Sanitizers.FORMATTING and Sanitizers.LINKS. This policy allows basic HTML formatting tags such as <b>, <i>, <u>, and hyperlinks via <a> tags. The sanitize() method then applies this policy to the input string and returns a cleaned version of the HTML content.

Let’s verify our sanitizer by inputting unsafe HTML and asserting that the output contains only the allowed tags:

String input = "<script>alert('XSS')</script><b>Hello</b> <a href='https://example.com'>link</a>";
String expectedOutput = "<b>Hello</b> <a href=\"https://example.com\" rel=\"nofollow\">link</a>";

String sanitized = HtmlSanitizerUtil.sanitize(input);
assertEquals(expectedOutput, sanitized);

In this test, we pass a string that includes a malicious <script> tag along with valid formatting and hyperlink elements. The sanitizer removes the script and retains the safe tags. The rel=”nofollow” attribute is added automatically to links as an additional safeguard.

4. Using OWASP HtmlPolicyBuilder for Flexible Sanitization

Although built-in policies offer convenience, we often need more control over which HTML elements and attributes to allow. The HtmlPolicyBuilder API offers a fluent approach to defining such custom policies.

Let’s implement a sanitizer that allows both block-level and inline formatting elements:

private static final PolicyFactory POLICY = new HtmlPolicyBuilder()
  .allowCommonBlockElements()
  .allowCommonInlineFormattingElements()
  .toFactory();

public static String sanitize(String html) {
    return POLICY.sanitize(html);
}

This implementation creates a policy that allows common block-level elements like <div>, <p>, <ul>, and <ol>, as well as inline elements such as <b>, <i>, and <em>. The sanitize() method uses this policy to remove any dangerous tags and attributes while preserving common layout and styling elements. The PolicyFactory instance is thread-safe and can be reused across multiple sanitization operations without re-instantiating.

Next, we verify this implementation with an assertion-based test that compares the sanitized result with the expected output:

String input = "<div onclick='alert(1)'><p><b>Text</b></p></div><script>alert('x')</script>";
String expectedOutput = "<div><p><b>Text</b></p></div>";

String sanitized = HtmlSanitizer.sanitize(input);
assertEquals(expectedOutput, sanitized);

In this case, the input contains unsafe event handlers and a <script> tag. Our custom policy strips out the dangerous attributes and elements, leaving behind only the permitted structural and formatting tags. This approach gives us a good balance between security and preserving user formatting for blog comments, CMS content, or discussion boards.

5. Creating a Custom Policy

In some applications, we might want to allow a different set of HTML elements or restrict certain attributes more tightly. The OWASP Java HTML Sanitizer provides a fluent API for building custom policies. Here’s an example of a more sophisticated policy configuration:

public class CustomHtmlSanitizer {
    private static final PolicyFactory POLICY = new HtmlPolicyBuilder()
      .allowElements("a", "p", "div", "span", "h1", "h2", "h3")
      .allowUrlProtocols("https")
      .allowAttributes("href").onElements("a")
      .requireRelNofollowOnLinks()
      .allowAttributes("class").globally()
      .allowStyling()
      .toFactory();

    public static String sanitize(String html) {
        return POLICY.sanitize(html);
    }
}

In this example, we construct a custom sanitization policy with the following rules:

  • Allowed Elements: The policy permits structural tags like <div>, <p>, and headings (<h1> to <h3>), as well as <a> and <span>
  • Allowed URL Protocols: Only HTTPS links are allowed, helping to prevent insecure HTTP links, which could lead to mixed-content issues
  • Link Attributes: The href attribute is permitted on <a> tags, and each link is automatically assigned a rel=”nofollow” attribute to reduce SEO abuse
  • Global Attributes: The class attribute is allowed on all elements, supporting CSS styling hooks
  • Inline Styling: Safe CSS styles are permitted via the style attribute, such as color, font-weight, and other non-harmful declarations

This approach gives us full control over the permitted structure and appearance of sanitized content while ensuring that any unsafe behavior, such as inline JavaScript, event handlers, or disallowed protocols, is effectively stripped out.

Let’s verify this with a test case:

String input = "<h1 class='title' style='color:red;'>Welcome</h1>"
  + "<a href='https://example.com' onclick='stealCookies()'>Click</a>"
  + "<script>alert('xss');</script>";

String expectedOutput = 
  "<h1 class=\"title\" style=\"color:red\">Welcome</h1><a href=\"https://example.com\" rel=\"nofollow\">Click</a>";

String sanitized = CustomHtmlSanitizer.sanitize(input);
assertEquals(expectedOutput, sanitized);

This kind of custom policy is beneficial when sanitizing user-generated content for blogs, forums, or CMS systems, where some flexibility in formatting is required, but not at the cost of security.

6. Alternative Approach: JSoup HTML Cleaner

While the OWASP Java HTML Sanitizer is highly secure and policy-driven, another popular library for sanitizing HTML in Java is JSoup. JSoup provides robust HTML parsing and cleaning capabilities, making it ideal for scenarios where we need to inspect or manipulate the DOM in addition to sanitization.

To get started, we first add the JSoup dependency to our pom.xml:

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.20.1</version>
</dependency>

Once added, we can implement a sanitizer that defines a safelist of allowed HTML elements and attributes. Here’s a sample implementation:

public class JsoupHtmlSanitizer {
    public static String sanitize(String html) {
        Safelist safelist = Safelist.basic()
          .addTags("h1", "h2", "h3")
          .addAttributes("a", "target")
          .addProtocols("a", "href", "http", "https");
        
        return Jsoup.clean(html, safelist);
    }
}

In this example, we start with Safelist.basic(), which permits basic HTML tags such as <b>, <i>, <u>, and <a>. Next, we extend it to allow heading tags like <h1>, <h2>, and <h3>.

Lastly, we also allow the target attribute on anchor tags, which enables opening links in a new tab when target=”_blank” is used and restricts link protocols to http and https.

To verify this implementation, let’s run a simple test:

String input = "<h1 onclick='x()'>Title</h1><a href='javascript:alert(1)' target='_blank'>Click</a>";
String expectedOutput = "<h1>Title</h1><a target=\"_blank\" rel=\"nofollow\">Click</a>";

String sanitized = JsoupHtmlSanitizer.sanitize(input);
assertEquals(expectedOutput, sanitized);

Unlike the OWASP sanitizer, JSoup uses a “safelist” model, which is more intuitive in some cases, especially when dealing with a predefined HTML structure or when we need to extract or modify specific HTML nodes before sanitizing.

Additionally, JSoup automatically adds rel=”nofollow” to <a> tags that use target=”_blank” to prevent reverse tabnabbing attacks, enhancing security by default.

7. Conclusion

In this article, we explored multiple methods for sanitizing HTML in Java applications to defend against XSS attacks.

The OWASP Java HTML Sanitizer is ideal when strict XSS protection and fine-grained, policy-driven control are required. JSoup is better suited for scenarios involving HTML parsing, manipulation, or when a simpler, safelist-based approach is sufficient.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW