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'
-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Java,
- CRUD operations in Spring Boot + JDBC
- Java Check Leap Year - Programs with Code Examples
- [fix] Java JDBC ConnectException: Connection refused
- How to add hours and minutes to Java Instant
- Java Program: Random Number Generator
- Java: The value of the local variable string is not used
- How to get list of all Java versions installed on macOS
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Java + Spring JDBC Template + Gradle Example
- Convert String to LocalDate in Java
- Remove Trailing zeros BigDecimal Java
- Java 8 Predicate Functional Interface isEqual() Method Example
- How to Hardcode Date in Java with Examples
- Java 8: Predicate negate() default Function Example
- Java: Collect Stream as ArrayList or LinkedList
- The Motivation Behind Generics in Java Programming
- How to Add/Subtract Days to the Current Date in Java
- Error: Can not find the tag library descriptor for
- Setting up JUnit 5 dependency with Maven Example
- Run Java Code Every Second
- How to create a tar.gz file using Java
- [Fix] java: integer number too large compilation error
- Java 8: Find the Max value in a List
- Your JBoss Application Server 7 is running However you have not yet added any users to be able to access the admin console
- Convert Java Array to ArrayList Code Example
More Posts:
- [Eclipse] Locate Preferences in macOS - MacOS
- How to Get the Relative Path of a file in Python Program - Python
- Pdf Text to Speech option in Mac OS X Preview App - Mac-OS-X
- Setting Java_Home Environment variable on Windows Operating System - Java
- pip/pip3 ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied - PIP
- Fix Microsoft Store Error Code: 0x80072EFD - Microsoft
- JavaScript: Check if variable is a number - JavaScript
- Fix: type argument is not within bounds of type-variable T - Java