BAEL-5644-escape-html-java (#14492)

This commit is contained in:
vunamtien 2023-07-28 21:44:51 +07:00 committed by GitHub
parent a8001c3a8e
commit 53aea2f855
3 changed files with 70 additions and 0 deletions

View File

@ -71,6 +71,11 @@
<artifactId>javax.annotation-api</artifactId>
<version>${annotation-api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${apache-commons-text.version}</version>
</dependency>
</dependencies>
<properties>
@ -80,6 +85,7 @@
<servlet-api.version>4.0.0</servlet-api.version>
<annotation-api.version>1.3.2</annotation-api.version>
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
<apache-commons-text.version>1.10.0</apache-commons-text.version>
</properties>
</project>

View File

@ -0,0 +1,21 @@
package com.baeldung.escapehtml;
import com.google.common.html.HtmlEscapers;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.web.util.HtmlUtils;
public class HtmlEscapeUtils {
public static String escapeWithApacheCommons(String input) {
return StringEscapeUtils.escapeHtml4(input);
}
public static String escapeWithGuava(String input) {
return HtmlEscapers.htmlEscaper().escape(input);
}
public static String escapeWithSpring(String input) {
return HtmlUtils.htmlEscape(input);
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.escapehtml;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class HtmlEscapeUnitTest {
@Test
public void whenInputContainAmpersand_thenEscape() {
String input = "AT&T";
String expected = "AT&amp;T";
assertEquals(expected, HtmlEscapeUtils.escapeWithApacheCommons(input));
assertEquals(expected, HtmlEscapeUtils.escapeWithGuava(input));
assertEquals(expected, HtmlEscapeUtils.escapeWithSpring(input));
}
@Test
public void whenInputContainDoubleQuotes_thenEscape() {
String input = "She said, \"Hello!\"";
String expected = "She said, &quot;Hello!&quot;";
assertEquals(expected, HtmlEscapeUtils.escapeWithApacheCommons(input));
assertEquals(expected, HtmlEscapeUtils.escapeWithGuava(input));
assertEquals(expected, HtmlEscapeUtils.escapeWithSpring(input));
}
@Test
public void whenInputContainManyHtmlSymbols_thenEscape() {
String input = "<p>This is a <strong>test</strong> string.</p>";
String expected = "&lt;p&gt;This is a &lt;strong&gt;test&lt;/strong&gt; string.&lt;/p&gt;";
assertEquals(expected, HtmlEscapeUtils.escapeWithApacheCommons(input));
assertEquals(expected, HtmlEscapeUtils.escapeWithGuava(input));
assertEquals(expected, HtmlEscapeUtils.escapeWithSpring(input));
}
@Test
public void whenInputContainNoHtmlSymbols_thenEscape() {
String input = "This is a plain text.";
assertEquals(input, HtmlEscapeUtils.escapeWithApacheCommons(input));
assertEquals(input, HtmlEscapeUtils.escapeWithGuava(input));
assertEquals(input, HtmlEscapeUtils.escapeWithSpring(input));
}
}