We can make use of the Apache Commons Text library to escape HTML characters using Java.
Let's take a look at an example using org.apache.commons.text.StringEscapeUtils.
import org.apache.commons.text.StringEscapeUtils;
public class JavaHTMLEscapeExample {
public static void main(String[] args) {
String htmlCode = "<html><head><title>Code2care Examples</title></head><body><h1>Welcome to Code2care</h1></body></html>";
String escapedHtml = StringEscapeUtils.escapeHtml4(htmlCode);
System.out.println(escapedHtml);
}
}
Output:
<html><head><title>Code2care
Examples</title></head><body><h1>Welcome to
Code2care</h1></body></html>
Note: Make sure to add the dependency to your build configuration file.
Add to Maven pom.xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.10.0</version>
</dependency>
Add to Gradle build.gradle
implementation group: 'org.apache.commons', name: 'commons-text', version: '1.10.0'
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!