Languages
[Edit]
EN

Java - escape HTML special characters using Spring Framework HtmlUtils.htmlEscape() method (attached unit test for most common cases)

3 points
Created by:
Marley-Marks
712

Quick solution:

public class HtmlUtils {

    public static String escape(String html) {
        return org.springframework.web.util.HtmlUtils.htmlEscape(html, "UTF-8");
    }
}

Unit tests:

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

class HtmlUtilsTest {

    @Test
    void shouldEscapeSpecialHtmlCharacters() {
        assertThat(HtmlUtils.escape("\"")).isEqualTo(""");
        assertThat(HtmlUtils.escape("<")).isEqualTo("&lt;");
        assertThat(HtmlUtils.escape(">")).isEqualTo("&gt;");
        assertThat(HtmlUtils.escape("&")).isEqualTo("&amp;");
        assertThat(HtmlUtils.escape("'")).isEqualTo("&#39;");
    }
}

 

Alternative titles

  1. Spring Framework - HtmlUtils.htmlEscape() method usage example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join