Overview
In this tutorial, we show you how to escape special HTML characters in Java Projects with Maven using the Apache Commons Lang library.Follow the steps mentioned below to develop this application.
Watch Tutorial
Project Structure
Create Java Projects with Maven
- Launch Eclipse IDE.
- Go to File-> New-> Others... Select Maven Project under Maven category then click Next.
- In New Maven Project wizard, select "Create a simpel project(skip archetype selection)" and click on Next
- In next wizard, type "com.jackrutorial" in the "Group ID:" field
- Type "EscapeSpecialCharactersExample" in the "Artifact Id:" field
- Packaging -> jar
- Click Finish.
Update pom.xml to include required dependencies
Open pom.xml file and add the following dependencies in it.<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jackrutorial</groupId> <artifactId>EscapeSpecialCharactersExample</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> </dependencies> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.4</version> <configuration> <source /> <target /> </configuration> </plugin> </plugins> </build> </project>
Create Main class
This tutorial, we use the escapeHtml() method of the StringEscapeUtils class in the Commons Lang library can be used to escapes the characters in a String using HTML entities.Special characters as follow:
& (ampersand)
" (double quote)
< (less than)
> (greater than)
Create a Main class under com.jackrutorial package and write the following code in it
package com.jackrutorial; import org.apache.commons.lang.StringEscapeUtils; public class Main { public static void main(String[] args) { // & (ampersand) becomes & System.out.print("& (ampersand) becomes"); System.out.println(" " + StringEscapeUtils.escapeHtml("&")); // " (double quote) becomes " System.out.print("\" (double quote) becomes"); System.out.println(" " + StringEscapeUtils.escapeHtml("\"")); // < (less than) becomes < System.out.print("< (less than) becomes"); System.out.println(" " + StringEscapeUtils.escapeHtml("<")); // > (greater than) becomes > System.out.print("> (greater than) becomes"); System.out.println(" " + StringEscapeUtils.escapeHtml(">")); } }
Run Application & Check Result
& (ampersand) becomes & " (double quote) becomes " < (less than) becomes < > (greater than) becomes >