How to escape special characters in java?

In Java, we can use Apache commons-text to escape the special characters in HTML entities.

Special characters as follow:

  1. <
  2. >
  3. &
pom.xml

  <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-text</artifactId>
      <version>1.8</version>
  </dependency>
EscapeSpecialChar.java

package com.mkyong.html;

import org.apache.commons.text.StringEscapeUtils;

// @deprecated as of 3.6, use commons-text StringEscapeUtils instead
//import org.apache.commons.lang3.StringEscapeUtils;

public class EscapeSpecialChar {

    public static void main(String[] args) {

        String testStr = "< > \" &";

        System.out.println("Original : " + testStr);

        System.out.println("Escaped : " + StringEscapeUtils.escapeHtml4(testStr));

    }
}

Output


Original : < > " &
Escaped : &lt; &gt; &quot; &amp;

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
7 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
8 Comment authors
AbhishekKiril ISAKOVbluelurkerBadaljesus israel perales martinez Recent comment authors
newest oldest most voted
bluelurker
Guest
bluelurker

How to escape special characters only from the value. ?
hello$ed
should be helloed

Swati Rohilla
Guest
Swati Rohilla

This is the BEST example. It helped me alot. Thanks alot. Big thanks to you.

michael
Guest
michael

how to escape special characters from xml file?

jesus israel perales martinez
Guest
jesus israel perales martinez

StringEscapeUtils.escapeXml(string);

priya
Guest
priya

I want to know about this library commons-lang.jar . I am working on jboss-eap-5.1 on server. Can I download this version jar file?

Badal
Guest
Badal

Actually the output is not right. Escaped should be < > " &.

Kiril ISAKOV
Guest
Kiril ISAKOV

Reference is a dead link.
I found the working link: http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringEscapeUtils.html
Please edit.
All best.

Abhishek
Guest
Abhishek

Facing problems with special characters. Have two application one connected to other through rest. SpringRestController.java snippet below Gson gson1 = new GsonBuilder().setDateFormat(“dd/MM/yyyy HH:mm:ss”).setPrettyPrinting().disableHtmlEscaping().create(); return gson1.toJson(lstCertNotification); so inside lstCertNotification we have another property strCertId for which the Value is N°123 …this degree symbol is creating problem Client code snippet below ClientResponse response = EECPCommonHelper.clientGetResponse(“searchCertificates”).put(ClientResponse.class,jsonString);; if (response.getStatus() != 200) { if(response.getStatus()==401){ try { FacesContext.getCurrentInstance().getExternalContext().redirect(“Error401.html”); } catch (IOException e) { e.printStackTrace(); } }else throw new RuntimeException(“Failed service call: HTTP error code : “+ response.getStatus()); }else{ response.bufferEntity(); Object strLstVendorServices = response.getEntity(Object.class); //response.getEntity(response.getEntityInputStream(), List.class); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); String entity = mapper.writeValueAsString(strLstVendorServices); TypeToken<List> token = new TypeToken<List>()… Read more »