How to escape HTML characters in Java


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:
&lt;html&gt;&lt;head&gt;&lt;title&gt;Code2care 
Examples&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Welcome to 
Code2care&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;

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'

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap