Escape Special HTML characters in Java Projects with Maven Tutorial


In this tutorial, we show you how to escape special HTML characters in Java Projects with Maven using the Apache Commons Lang library.

Escape Special HTML characters in Java

Follow the steps mentioned below to develop this application.

Watch Tutorial

Project Structure

Project Structure Escape Special Characters

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="" 

     <source />
     <target />

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 &amp;
" (double quote) becomes &quot;
< (less than) becomes &lt;
> (greater than) becomes &gt;


Previous Post
Next Post

post written by: