eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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 – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

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 – LSS – NPI (cat=Security/Spring Security)
announcement - icon

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)