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

Note: Make sure to add the dependency to your build configuration file.

Add to Maven pom.xml

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:

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